Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference previous value in v-for in vue.js

I have a grid created with vue.js, but I've having difficulty getting the right index for the values after a keyword filter is applied.

<tbody v-for="
      entry in data
    | filterBy filterKey
    | orderBy sortKey sortOrders[sortKey]">
        <tr v-if="$index == 0 || ($index > 0 && entry['value'] != data[$index-1]['value'])">
            <td class="Header" colspan="3">
                    VALUE: @{{{entry["value"]}}}
            </td>
        </tr>
 ...

In this case, {{$index}} gives 0, 1, 2, 3 etc. However, when a filter is applied, only parts of the data are visible on-screen. (i.e. only the entries at indexes 6 and 8) Unfortunately, $index is still incrementing by 1 starting at 0, making it impossible to reference the previous entry. What is the correct way to reference the previous entry?

(I want to check if a certain part of the entry is different than the one above it, and if it is, create a new header. I have it working except for when a keyword filter is applied)

like image 869
Skeets Avatar asked Sep 03 '25 16:09

Skeets


1 Answers

Here is the jsfiddle as I said

https://jsfiddle.net/sg4jtzzw/

The gist of it is that

A computed property is added which encapsulates filtering and sorting on this.data

computed:{
    special: function(){
        var key= this.filt;
        return this.data.filter(function(row){ 
            return row.indexOf(key)!= -1;   
        }).sort(); 
    }
}

In ready function, we initialize a $watch to update prev according to value of special

ready: function(){
  var self = this;
  self.prev= [];
  this.$watch('special',function(newVal, oldVal){
    self.prev = oldVal;  
  });
}

Html portion is quite simplified and compact

<div v-for="item in special">
  <span v-if=" previousList(item)== true"> Old </span>
  {{ item }}
 </div>

Note: both filter() and sort() are js functions, not vue functions, and are case-sensitive. The code would be less verbose if I were to use vue filters, but I don't how to. As using built-in filters is not recommended approach, I don't advise using them either

To know about recommended approach on filters, you can read the discussion on github

like image 64
Raj Kamal Avatar answered Sep 05 '25 05:09

Raj Kamal