vue实现筛选列表
Vue 实现筛选列表的方法
数据绑定与列表渲染
使用 v-for 指令渲染原始列表,绑定到 data 中的数组。例如:
data() {
return {
items: [
{ id: 1, name: 'Apple', category: 'Fruit' },
{ id: 2, name: 'Carrot', category: 'Vegetable' }
],
filterText: '',
filterCategory: ''
}
}
模板中渲染列表:
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }} ({{ item.category }})
</li>
</ul>
计算属性实现筛选逻辑
通过 computed 动态计算筛选结果,避免直接修改原始数据:
computed: {
filteredItems() {
return this.items.filter(item => {
const matchesText = item.name.toLowerCase().includes(
this.filterText.toLowerCase()
);
const matchesCategory = this.filterCategory === '' ||
item.category === this.filterCategory;
return matchesText && matchesCategory;
});
}
}
添加筛选交互控件
在模板中添加输入框和下拉菜单:
<input
type="text"
v-model="filterText"
placeholder="Search by name...">
<select v-model="filterCategory">
<option value="">All Categories</option>
<option value="Fruit">Fruit</option>
<option value="Vegetable">Vegetable</option>
</select>
优化性能
对于大数据量场景,可添加防抖处理:
data() {
return {
debounceTimeout: null
}
},
methods: {
handleInput() {
clearTimeout(this.debounceTimeout);
this.debounceTimeout = setTimeout(() => {
this.filterText = event.target.value;
}, 300);
}
}
多条件筛选扩展
支持更复杂的筛选条件时,可扩展计算属性:
computed: {
filteredItems() {
return this.items.filter(item => {
// 多个条件组合
return (
(this.filterConditions.priceMin === '' ||
item.price >= this.filterConditions.priceMin) &&
(this.filterConditions.inStock ||
!this.filterConditions.inStockOnly)
);
});
}
}
使用第三方库
对于复杂需求,可考虑使用专用库:
npm install lodash.debounce vue-multiselect
示例集成:
import debounce from 'lodash.debounce';
export default {
methods: {
handleInput: debounce(function(e) {
this.filterText = e.target.value;
}, 300)
}
}






