Vue.js 空过滤结果 [英] Vue.js empty filter results
问题描述
在 Vue 中,我必须过滤一些数据:
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?
编辑
我目前正在执行以下操作,我认为这是一种很棘手的解决方法:
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:
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
});
}
})
推荐答案
Vue 2.x (Update)
现在只能在 Vue 2.x 中使用过滤器,如文档所述, 文本内插:
Vue 2.x 过滤器只能在 mustache 绑定中使用.要在指令绑定中实现相同的行为,您应该改用 Computed 属性.
Vue 2.x filters can only be used inside mustache bindings. To achieve the same behavior inside directive bindings, you should use Computed properties instead.
您可以使用 JavaScript 内置的 filter
方法和计算属性来实现相同的行为.
You can achieve same behavior with JavaScript built-in filter
method and computed property.
<input v-model="searchQuery">
<span v-if="!filteredItems.length">No results.</span>
<ul>
<li v-for="item in filteredItems"></li>
</ul>
computed: {
filteredItems: function () {
var self = this;
return self.items.filter(function (item) {
return item.indexOf(self.searchQuery) !== -1;
})
}
}
Vue 1.x(原答案)
目前有两种方法.在所有情况下,模板看起来都一样.
Vue 1.x (Original Answer)
There are two ways at the moment. In all cases, template can look the same.
<input v-model="searchQuery">
<span v-if="!filteredItems.length">No results.</span>
<ul>
<li v-for="item in filteredItems"></li>
</ul>
过滤器
通过 $options
访问的原始 filterBy
方法.
filterBy
Original filterBy
method accessed via $options
.
computed: {
filteredItems: function () {
return this.$options.filters.filterBy(this.items, this.searchQuery);
}
}
$eval
更简洁的方法.Eval 表达式就像您在模板中所做的那样.
$eval
A little bit cleaner approach. Eval expression like you would do inside your template.
computed: {
filteredItems: function () {
return this.$eval('items | filterBy searchQuery');
}
}
这篇关于Vue.js 空过滤结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!