Wolfgang Müller Wolfgang Müller - 5 months ago 22
JSON Question

How can I filter results "live" with Vue?

I have an input v-model and I want to filter through a product list.

Here is my filter. The problem is that it only works if the item name matches the input exactly. How can I modify the filter to see any partial matches as the input is being typed?

Vue.filter('byName', function (data, input) {

if(input){
return data.filter(function (item) {
return item.name == input
});
}

return data

});

Answer

If you want to see "live" results, then you need to code your filter so that it returns items that partially match.

The simplest way is to use the startsWith() method. The following filter uses startsWith() to match all items that start with the input:

Vue.filter('byName', function (data, input) {
  if(input){
    return data.filter(function (item) {
      // we check if the item's name starts with the input
      return item.name.startsWith(input);
    });
  }
  return data
});

Here is a JSFiddle of that filter in action.

On the other hand, if you wanted to return items that match anywhere, not just ones that started with the input, you can use String.prototype.indexOf().

To do this, replace

// we check if the item's name starts with the input
return item.name.startsWith(input);

with

// we check if the item's name contains the input as a substring
return item.name.indexOf(input) > -1;
Comments