Nicolay Hekkens
Nicolay Hekkens

Reputation: 530

Vue v-for changing from version 1 to version 2

I'm learning Vue.js and found this fiddle that does exactly what I want to do.

Here is the fiddle: https://jsfiddle.net/os7hp1cy/48/

I integrated this and am getting this error:

invalid expression: v-for="user in users | filterBy searchKey | paginate"

So I've done some digging and I see it has changed from version 1 to 2. However, I don't know how to fix this.

<li v-for="user in users | filterBy searchKey | paginate">{{ user.name }}</li>

I would like to replace this with something that Vue 2 will support and will work the same way.

Upvotes: 0

Views: 101

Answers (1)

thanksd
thanksd

Reputation: 55644

As of Vue version 2, filters can only be used inside text interpolations ({{ }} tags). See the documentation for migrating from Vue version 1.

You can use a computed property to filter the users and use that computed property in the v-for directive instead:

computed: {
  filteredUsers: function() {
    let key = this.searchKey.toUpperCase();
    return this.users.filter((user) => {
      return user.name.toUpperCase().indexOf(key) !== -1
    })
  },
  paginatedUsers: function() {
    var list = this.filteredUsers;
    this.resultCount = list.length
    if (this.currentPage >= this.totalPages) {
      this.currentPage = this.totalPages
    }
    var index = this.currentPage * this.itemsPerPage
    return list.slice(index - 1, index - 1 + this.itemsPerPage)
  }
}
<li v-for="user in paginatedUsers">{{ user.name }}</li>

Also, when using v-for to generate a range of numbers like you do for your page numbers, Vue version to starts the index at 1 instead of 0. So, you'll need to update the logic depending on a starting index of 0 as well.

Here's a working fiddle.

Upvotes: 3

Related Questions