Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: can't orderBy in v-for

I've upgraded to Vue.js 2.0.5 and orderBy in a v-for seems to not be working anymore

<li v-for="c in rooms | orderBy 'last_iteraction'"> 

outputs

  • invalid expression: v-for="c in rooms | orderBy 'last_iteraction'"

anyone knows how to solve?

like image 720
Christian Benseler Avatar asked Nov 09 '16 17:11

Christian Benseler


2 Answers

orderBy Filter is removed in vue.js v-2.

Quoted from vue.js docs

Instead of:

<p v-for="user in users | orderBy 'name'">{{ user.name }}</p>

Use lodash’s orderBy (or possibly sortBy) in a computed property:

<p v-for="user in orderedUsers">{{ user.name }}</p>

computed: {   orderedUsers: function () {     return _.orderBy(this.users, 'name')   } } 

Reference:

https://vuejs.org/v2/guide/migration.html#Replacing-the-orderBy-Filter

like image 134
Khorshed Alam Avatar answered Oct 17 '22 20:10

Khorshed Alam


You can also use vue2 filters package.

  1. First install it using npm.

npm install vue2-filters

  1. Then, add it in your component or globally.
import Vue from 'vue' import Vue2Filters from 'vue2-filters'    Vue.use(Vue2Filters) 
  1. To use one of the predefined methods (such as limitBy, filterBy, find, or orderBy) in your component, you also need to add Vue2Filters.mixin to mixin list:
import Vue2Filters from 'vue2-filters'  export default {   ...   mixins: [Vue2Filters.mixin],   ... } 
  1. After that use it in the template
 <li v-for="c in orderBy(rooms,'last_iteraction')"> 

There is a list of predefined filters.check it out.

Reference:

https://github.com/freearhey/vue2-filters

like image 21
Pulkit chadha Avatar answered Oct 17 '22 20:10

Pulkit chadha