vue实现标签筛选
实现标签筛选的基本思路
在Vue中实现标签筛选功能通常涉及以下核心步骤:数据绑定、筛选逻辑和UI交互。通过v-model或计算属性管理选中状态,利用数组方法过滤数据。
数据准备与渲染
定义标签数组和待筛选的数据列表,使用v-for循环渲染标签按钮和内容列表。标签数据可设为对象数组,包含id和name属性;内容数据需包含与标签关联的字段(如tagIds)。
<template>
<div>
<div class="tags">
<button
v-for="tag in tags"
:key="tag.id"
@click="toggleTag(tag.id)"
:class="{ active: selectedTags.includes(tag.id) }"
>
{{ tag.name }}
</button>
</div>
<div class="content-list">
<div v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</div>
</div>
</div>
</template>
状态管理与筛选逻辑
使用ref或reactive管理选中标签的状态,通过计算属性实现动态筛选。当没有选中标签时默认显示全部内容,选中后过滤出包含任意选中标签的项。
<script setup>
import { ref, computed } from 'vue';
const tags = ref([
{ id: 1, name: '前端' },
{ id: 2, name: '后端' },
{ id: 3, name: '移动端' }
]);
const items = ref([
{ id: 1, name: 'Vue项目', tagIds: [1] },
{ id: 2, name: 'Spring项目', tagIds: [2] },
{ id: 3, name: 'React Native项目', tagIds: [1, 3] }
]);
const selectedTags = ref([]);
const toggleTag = (tagId) => {
const index = selectedTags.value.indexOf(tagId);
if (index > -1) {
selectedTags.value.splice(index, 1);
} else {
selectedTags.value.push(tagId);
}
};
const filteredItems = computed(() => {
if (selectedTags.value.length === 0) return items.value;
return items.value.filter(item =>
item.tagIds.some(tagId => selectedTags.value.includes(tagId))
);
});
</script>
样式优化与交互反馈
为选中标签添加视觉反馈,通过CSS高亮显示当前激活的标签。可结合过渡效果提升用户体验。
<style>
.tags button {
margin: 5px;
padding: 5px 10px;
background: #eee;
border: none;
cursor: pointer;
}
.tags button.active {
background: #42b983;
color: white;
}
.content-list {
margin-top: 20px;
}
</style>
多选与单选模式切换
通过模式变量控制筛选逻辑。单选模式下点击新标签会替换当前选中项,多选模式则累加选择。
const isMultiSelect = ref(true);
const toggleTag = (tagId) => {
if (!isMultiSelect.value) {
selectedTags.value = selectedTags.value[0] === tagId ? [] : [tagId];
} else {
const index = selectedTags.value.indexOf(tagId);
if (index > -1) {
selectedTags.value.splice(index, 1);
} else {
selectedTags.value.push(tagId);
}
}
};
性能优化建议
对于大型数据集,采用虚拟滚动或分页加载。可在筛选前对数据进行预处理,建立标签索引提高过滤效率。
// 建立标签索引的示例
const tagIndex = {};
items.value.forEach(item => {
item.tagIds.forEach(tagId => {
if (!tagIndex[tagId]) tagIndex[tagId] = [];
tagIndex[tagId].push(item);
});
});






