如何在Vue.js中仅使用data和methods实现列表搜索过滤功能
Vue.js仅用data和methods实现搜索过滤的方案
完全可以仅通过data和methods实现搜索过滤功能,你现有代码混用了jQuery的DOM操作逻辑,没有遵循Vue的数据驱动思路,修正方案如下:
现有代码问题梳理
this.search已经是通过v-model双向绑定的字符串,不需要调用.val()获取值- 不要直接修改原始的待筛选数组,否则筛选一次后原始数据就会丢失,需要额外加字段存储原始数据
Array.filter()是返回符合条件新数组的方法,你写法中的.toggle()是jQuery的DOM操作方法,Vue不需要直接操作DOM,只要修改渲染用的数组即可
修正后代码
Vue实例代码
var fil = new Vue ({ el: '#app', data: { search: '', // 存储原始待筛选数据 originProL: ['css', 'c++', 'cs#'], // 用来渲染的筛选后数组 proL: ['css', 'c++', 'cs#'] }, methods: { filter: function(){ const searchKey = this.search.trim().toLowerCase(); // 无搜索关键词时返回原始数组 if (!searchKey) { this.proL = this.originProL; return; } // 过滤原始数组得到符合条件的结果赋值给渲染数组 this.proL = this.originProL.filter(item => { return item.toLowerCase().indexOf(searchKey) > -1; }); } } });
HTML代码
<div id="app"> <div> <input @keyup="filter()" type="text" v-model="search" placeholder="Search title.."/> </div> <div id="pro"> <h4 v-for="item in proL" :key="item">{{item}}</h4> </div> </div>
内容的提问来源于stack exchange,提问作者Khaled Altarhoni
相关产品推荐
相关产品推荐

