Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS: How to Access the Previous Item in v-repeat

I have a table that fetches some JSON from a Laravel API to populate the rows. I am using VueJS and the v-repeat:

<tbody>
  <tr v-repeat="entry: entries">
    <td>@{{ entry.id }} </td>
    <td>@{{ entry.distance }} km</td>
    <td>@{{ entry.consumption }} l</td>
    <td>@{{ getPrice(entry) + ' €'}}</td>
    <td>@{{ getCost(entry) + ' €'}}</td>
    <td>@{{ getAverageConsumption(entry) + ' l' }}</td>
    <td>@{{ getAverageCost(entry) + ' €' }}</td>
    <td>@{{ getCostPerDay(entry) + ' €' }}</td>
    <td>@{{ this.getDate(entry) }}</td>
  </tr>
</tbody>

Now I want to calculate the AverageCostPerDay(). Problem is, that I need to access the previous item in the iteration to make a comparison on how many days passed.

How do I access previous items with v-repeat in VueJS? And how could my getCostPerDay() method look like?

like image 432
LoveAndHappiness Avatar asked Jul 27 '15 04:07

LoveAndHappiness


People also ask

What is $El in Vue?

The $el option in Vue provides Vue with an existing HTML element to mount the Vue instance generated using the new keyword. this. $el. querySelector is used to access HTML elements and modify the element's properties.

What is $V in Vue?

$v is an object that calls vuelidate (at the time of writing the comment, supported in version Vue. js 2.0), which is intended to check every input, which is made in a non-html form.

What is $data in Vue?

data function is called by Vue while creating a component instance and returns an object, These data include in Vuejs reactive and store the instance data as $data object. Important points about data function. It can be arrow functions or data property or normal es5 function. It should always return an object.

What is reactive dependency in Vue?

Reactive dependencies are those that are observable, like data properties or Vuex state. Non-reactive dependencies would be something like a simple variable or something from local-storage.


1 Answers

In v2 of vue.js, you need to this form of v-for to get the index:

v-for="(item, index) in items"

You can then use items[index - 1] to get the previous value (making sure your function checks it isn't undefined).

like image 159
Nanki Avatar answered Oct 02 '22 18:10

Nanki