VueJS: how to access the previous item in v-repeat

I have a table that retrieves some JSON from the Laravel API to populate rows. I use VueJS and 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 value of AverageCostPerDay (). The problem is that I need to access the previous item in an iteration in order to compare how many days have passed.

How do I access previous items using v-repeat in VueJS? And what might my getCostPerDay () method look like ?

+4
source share
3 answers

You can use the variable $indexalong with the entriesfollowing

        <td>@{{ getCostPerDay(entries[$index-1]) + ' €' }}</td>

$index .

+3

v2 vue.js v-for, :

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

items[index - 1] (, , undefined).

+1

I solved this by creating a method that adds a point to the current index, for example:

getNextItemIndex: function(entry) {
    var currentIndex = this.entries.indexOf(entry);
    return (currentIndex + 1);
},

getNextItemDate: function(entry) {
    var nextDate = moment(this.entries[this.getNextItemIndex(entry)].date);
    return nextDate;
},

getTimeDifferenceToNextEntry: function(entry) {
    var entryDate = moment(entry.date);

    var timeDifference = entryDate.diff(this.getNextItemDate(entry), 'hours') / 24;

    return timeDifference.toFixed(3);
},

getCostPerDay: function(entry) {
    var costPerDay = this.getCost(entry) / this.getTimeDifferenceToNextEntry(entry);


    return costPerDay.toFixed(2);

    // console.log(dateDifference);

    var priceRatio = entry.price / nextPrice / 1000;

    return priceRatio.toFixed(3);
    // return previousEntry.price;
}
0
source

Source: https://habr.com/ru/post/1599791/


All Articles