Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
sven Avatar asked May 02 '17 22:05

sven


1 Answers

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">
like image 132
Bert Avatar answered Sep 18 '22 22:09

Bert