I have a list of users from an array. And I want to filter them based on the search box(name) at the top. I saw that there are filters in VueJS 1. But not available in VuesJS 2.
I have done this by having my property "array" with the data elements and a computed property (array as well) with the filtered elements. The HTML renders the filtered elements. I have a property bound to the text box. For simplicity, something like this:
data: function () {
return{
search: '',
customers: [
{ id: '1', name: 'user 1', profile_pic: 'https://i.stack.imgur.com/CE5lz.png', email:'ab@gmail.com', phone:'+91959657248', unread:'0' },
{ id: '2', name: 'user 2', profile_pic: 'https://i.stack.imgur.com/CE5lz.png', email:'abcd@gmail.com', phone:'+919456664023', unread:'0' },
{ id: '3', name: 'user 3', profile_pic: 'https://i.stack.imgur.com/CE5lz.png', email:'test@gmail.com', phone:'+919566565065', unread:'0' },
{ id: '4', name: 'user 4', profile_pic: 'https://i.stack.imgur.com/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;});
}
}
Bind your HTML to filteredCustomers. You should now have a reactive HTML based on what you type on search. That "filter" method is native JavaScript for arrays, I lower-cased both values to make it case insensitive.
Here's a working example in fiddle: https://jsfiddle.net/dkmmhf5y/1/
Edit: Added fiddle and code corrections in computed property