Reputation: 727
Just following a tutorial about Vue filter on v-for directive in Vue 1.x, the author was using multiple filters in one v-for
directive, e.g.
<ul v-for="post in posts | filterBy nameFilter in 'name' | filterBy catFilter in 'cat'"></ul>
As far as I know from the official documentation, this syntax is no longer being used in Vue 2.0, I tried to rewrite this line of code into
<ul v-for="post in nameFilter | catFilter"></ul>
I also created two computed functions nameFilter
and cateFilter
to filter out the posts by name and category. My code is not working, it only listens to the first filter which is nameFilter
, cateFilter
has no effect at all.
So I was wondering in Vue 2.0, is that still possible to add multiple filters in v-for
directive? If it is possible, could you guys please advise the syntax?
If that's impossible, does that mean that I need to create one filter function to do all the filter logic in that single function?
Thanks in advance.
Upvotes: 0
Views: 1926
Reputation: 727
Found the answer from here
Basically, we only need one computed function to return the filtered data for v-for
directive, e.g.
<ul v-for="post in filteredPosts"></ul>
If we want to add multiple, just chain all your javascript native .filter
functions in that function and return the data. In my case, it would be something like this:
computed: {
filteredPost: function () {
var self = this
return self.posts
.filter(function (post) {
return post.title.indexOf(self.searchQuery) !== -1;
})
.filter(function(post) {
return (post.category.includes(self.selectedCategory))
})
}
}
self.searchQuery
and self.selectedCategory
are just data properties for this Vue instance in my example, the key takeaway is one computed function with multiple .filter()
functions chaining together.
Hope that will help.
Upvotes: 4