In Vue, I have to filter through some data:
<input v-model="search">
<ul>
<li v-repeat="photo in photos | filterBy search in 'name'">
<img src="{{ photo.src }}" alt="{{ photo.name }}">
</li>
<li v-if="!photos.length">
No results, sorry!
</li>
</ul>
How can I detect empty filter results and display an appropriate message to the user?
EDIT
I am currently doing the following which I feel is a hacky workaround:
HTML:
<input v-model="search">
<ul>
<li v-repeat="photo in photos">
<img src="{{ photo.src }}" alt="{{ photo.name }}">
</li>
<li v-if="!photos.length">
No results, sorry!
</li>
</ul>
Javascript:
var v = new Vue({
data: {
allPhotos: [...],
photos: [],
search: '',
},
ready: function () {
var filter = Vue.filter('filterBy');
var self = this;
this.$watch('search', function () {
self.photos = filter(self.allPhotos, self.search, 'name');
}, {
immediate: true
});
}
})
This will only work with Vue 1.0, even then you should just be using a computed property. I'll leave this answer here just in case.
You could use
vm.$eval
and a computed property to do this as well.and use something like
Vue 2.x (Update)
In Vue 2.x filters can now only be used, as docs say, inside text interpolations:
You can achieve same behavior with JavaScript built-in
filter
method and computed property.Vue 1.x (Original Answer)
There are two ways at the moment. In all cases, template can look the same.
filterBy
Original
filterBy
method accessed via$options
.$eval
A little bit cleaner approach. Eval expression like you would do inside your template.
In HTML:
In JS, you need to use computed properties like this:
Demo: http://jsfiddle.net/crswll/Lr9r2kfv/37/
HTML/CSS solution (just in case, if you still trying to fix it after 2 years)
Also codepen link here