我有一个数组中的用户列表。我想根据顶部的搜索框(名称)过滤它们。我看到 VueJS 1 中有过滤器。但在 VueJS 2 中不可用。如何在 VueJS 2 中实现这一点
<input type="text" v-model="search"/>
<div class="row profile" v-for="customer in customers">
<div class="col-md-offset-1 col-md-3"><img :src="customer.profile_pic" class="profile-pic" /></div>
<div class="col-md-8"><h4 class="name">{{customer.name}}</h4></div>
</div>
<script>
data: function () {
return{
search: '',
customers: [
{ id: '1', name: 'user 1', profile_pic: '/image/CE5lz.png', email:'ab@gmail.com', phone:'+91959657248', unread:'0' },
{ id: '2', name: 'user 2', profile_pic: '/image/CE5lz.png', email:'abcd@gmail.com', phone:'+919456664023', unread:'0' },
{ id: '3', name: 'user 3', profile_pic: '/image/CE5lz.png', email:'test@gmail.com', phone:'+919566565065', unread:'0' },
{ id: '4', name: 'user 4', profile_pic: '/image/CE5lz.png', email:'sample@gmail.com', phone:'+916466004566', unread:'0' }
]
}
}
</script>
最佳答案
我通过将我的属性“数组”与数据元素和一个计算属性(也是数组)与过滤元素来实现这一点。 HTML 呈现过滤后的元素。我有一个绑定(bind)到文本框的属性。 为简单起见,像这样:
data: function () {
return{
search: '',
customers: [
{ id: '1', name: 'user 1', profile_pic: '/image/CE5lz.png', email:'ab@gmail.com', phone:'+91959657248', unread:'0' },
{ id: '2', name: 'user 2', profile_pic: '/image/CE5lz.png', email:'abcd@gmail.com', phone:'+919456664023', unread:'0' },
{ id: '3', name: 'user 3', profile_pic: '/image/CE5lz.png', email:'test@gmail.com', phone:'+919566565065', unread:'0' },
{ id: '4', name: 'user 4', profile_pic: '/image/CE5lz.png', email:'sample@gmail.com', phone:'+916466004566', unread:'0' }
]
},
computed:
{
filteredCustomers:function()
{
var self=this;
return this.customers.filter(function(cust){return cust.name.toLowerCase().indexOf(self.search.toLowerCase())>=0;});
}
}
将您的 HTML 绑定(bind)到 filteredCustomers。您现在应该有一个基于您在搜索中键入的内容的响应式 HTML。 “过滤器”方法是数组的原生 JavaScript,我将两个值都小写以使其不区分大小写。
这是 fiddle 中的一个工作示例: https://jsfiddle.net/dkmmhf5y/1/
编辑:在计算属性中添加了 fiddle 和代码更正
关于vuejs2 - 在文本框 VueJS 2 中键入时搜索列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41712791/