Vue.js中实现数组过滤功能时遇到的问题如何解决?
问题原因
- 你把
computed配置项错误嵌套在data()内部了,二者是Vue组件同级的顶层配置属性,嵌套会导致计算属性不生效、代码报错 - 你实现了过滤排序逻辑的计算属性,但虚拟列表绑定的数据源还是未经过滤的原始列表,没有用到处理后的结果
computedItems中直接修改原数组的item对象属性,属于直接修改原数据的非规范写法,容易引发副作用
实现方案说明
使用v-model绑定搜索关键词实现过滤是完全可行的,属于该场景下的常规实现方案,你之前的功能失效仅由代码书写错误导致,修正后即可正常运行。
修正后代码
JS配置部分
// data和computed为同级配置,不要嵌套 data() { return { searchString: '', sortKey: 'name', checked: false, Item, items: [{ price: '1', name: 'mm' }] } }, computed: { // 给item添加唯一key,返回新对象避免修改原数据 computedItems() { return this.items.map((item, index) => { return {...item, key: `item_${index}`} }) }, // 经过排序、过滤后的最终渲染列表 processedList() { const searchString = this.searchString.trim().toLowerCase() const listClone = [...this.computedItems] // 先执行排序逻辑 const sortedArray = listClone.sort((a, b) => { if (a[this.sortKey] < b[this.sortKey]) return -1 if (a[this.sortKey] > b[this.sortKey]) return 1 return 0 }) // 无搜索词直接返回排序结果,有搜索词返回过滤结果 if (!searchString) return sortedArray return sortedArray.filter(item => item.name.toLowerCase().includes(searchString)) } }
HTML模板部分
<div class="wrapper"> <input type="text" v-model="searchString" placeholder="search items from here" /> <br /> <virtual-list class="list" style="height: 360px; overflow-y: auto" data-key="key" :keeps="20" <!-- 绑定经过处理的最终数据源 --> :data-sources="processedList" :data-component="Item" /> <hr /> </div>
内容的提问来源于stack exchange,提问作者user17525310
相关产品推荐
相关产品推荐

