如何使用 Vue 过滤"live"的结果?



我有一个输入V模型,我想通过产品列表过滤。

这是我的过滤器。问题在于,仅当项目名称与输入完全匹配时才有效。在输入时,如何修改过滤器以查看任何部分匹配?

Vue.filter('byName', function (data, input) {
if(input){
    return data.filter(function (item) {
        return item.name == input
    });
}
return data
});

如果要查看" live"结果,则需要编码过滤器,以便它返回部分匹配的项目。

最简单的方法是使用startsWith()方法。以下过滤器使用startsWith()匹配以输入开头的所有项目:

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
});

这是该过滤器中的JSFIDDLE。

另一方面,如果您想返回匹配 wherewhere 的项目,而不仅仅是从输入开始的项目,则可以使用String.prototype.indexOf()

为此,替换

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

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

最新更新