5

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?

2 Answers 2

7

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">
Sign up to request clarification or add additional context in comments.

Comments

-2

Template

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

vue js

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.