Vue比较实用的搜索过滤器,转载自这里

效果

过滤器效果

Html代码

<div id="app">
    <input v-model='search' />
    <ul v-if="searchData.length > 0">
      <li v-for="item in searchData">{{item.name}},价格:¥{{item.price}}</li>
    </ul>
    <div v-else>暂无数据</div>
</div>

Js代码

var vm = new Vue({
  el: '#app',
  data: {
    search: '',
    products: [{
      name: '苹果',
      price: 25,
      category: "水果"
    }, {
      name: '香蕉',
      price: 15,
      category: "水果"
    }, {
      name: '雪梨',
      price: 65,
      category: "水果"
    }, {
      name: '宝马',
      price: 2500,
      category: "汽车"
    }, {
      name: '奔驰',
      price: 10025,
      category: "汽车"
    }, {
      name: '柑橘',
      price: 15,
      category: "水果"
    }, {
      name: '奥迪',
      price: 25,
      category: "汽车"
    }]
  },
  computed: {
    searchData: function() {
      var search = this.search;

      if (search) {
        return this.products.filter(function(product) {
          return Object.keys(product).some(function(key) {
            return String(product[key]).indexOf(search) > -1
          //原文使用使用了小写转换:
          //return String(product[key]).toLowerCase().indexOf(search) > -1
          })
        })
      }

      return this.products;
    }
  }
})

标签: Vue

评论已关闭