sven
sven

Reputation: 599

Vue.js: Sort a list based on method

I'm fetching some raw data and displaying a list of items. Each item has a complex property that I generate with a method (which is not a computed property). That property might change on user input. Is it possible to sort the items of the list based on that property?

HTML:

<ul>
  <li v-for="item in items">
    <span>{{ calculateComplexProperty(item.time) }}</span>
  </li>
</ul>

JavaScript:

calculateComplexProperty: function (time) {
  // this.distance is an external factor that is not a property of the list item, 
  // and that can be manipulated by the user
  var speed = time * this.distance;

  return speed;
}

So each item has a time value that is manipulated by a global, dynamic factor, "distance". The idea is to automatically sort the items whenever the "distance" changes and also, to update the "speed" property. Is this possible?

Upvotes: 5

Views: 3323

Answers (2)

Rayees Pk
Rayees Pk

Reputation: 3033

Template

<li v-for="item in sortedItems(items)">

vue js

computed:{
    sortedItems(items){
        return _.orderBy(items, 'time', 'asc');
    }
}

Upvotes: -2

Bert
Bert

Reputation: 82499

How about this?

computed:{
    sortedItems(){
        return this.items.sort((a,b) => 
             this.calculateComplexProperty(a.time) - this.calculateComplexProperty(b.time))
    }
}

Template

<li v-for="item in sortedItems">

Upvotes: 7

Related Questions