vue实现分类查找
Vue 实现分类查找的方法
分类查找功能通常需要结合 Vue 的数据绑定、计算属性和方法来实现。以下是几种常见的实现方式:
使用计算属性过滤数据
computed: {
filteredItems() {
if (!this.selectedCategory) return this.items;
return this.items.filter(item => item.category === this.selectedCategory);
}
}
在模板中使用 v-for 遍历 filteredItems 即可显示分类结果。
使用 watch 监听分类变化
data() {
return {
selectedCategory: '',
filteredItems: []
}
},
watch: {
selectedCategory(newVal) {
this.filteredItems = newVal
? this.items.filter(item => item.category === newVal)
: this.items;
}
}
使用路由参数实现分类
// 路由配置
{
path: '/products/:category?',
component: Products
}
// 组件内
computed: {
filteredItems() {
const category = this.$route.params.category;
return category
? this.items.filter(item => item.category === category)
: this.items;
}
}
使用 Vuex 管理分类状态
// store
state: {
items: [],
currentCategory: ''
},
getters: {
filteredItems: state => {
return state.currentCategory
? state.items.filter(item => item.category === state.currentCategory)
: state.items;
}
}
实现多级分类查找
对于多级分类,可以递归查找或使用更复杂的过滤条件:
computed: {
filteredItems() {
return this.items.filter(item => {
return (
(!this.category1 || item.category1 === this.category1) &&
(!this.category2 || item.category2 === this.category2)
);
});
}
}
分类查找组件示例
<template>
<div>
<select v-model="selectedCategory">
<option value="">所有分类</option>
<option v-for="cat in categories" :value="cat">{{ cat }}</option>
</select>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '商品A', category: '电子产品' },
{ id: 2, name: '商品B', category: '服装' }
],
selectedCategory: ''
};
},
computed: {
categories() {
return [...new Set(this.items.map(item => item.category))];
},
filteredItems() {
if (!this.selectedCategory) return this.items;
return this.items.filter(item => item.category === this.selectedCategory);
}
}
};
</script>
这些方法可以根据具体需求选择或组合使用,实现灵活的分类查找功能。







