vue实现tag效果
实现基本标签结构
使用 Vue 的模板语法创建标签容器和单个标签元素。通过 v-for 动态渲染标签列表,结合 v-bind:key 确保渲染性能。
<template>
<div class="tag-container">
<span
v-for="tag in tags"
:key="tag.id"
class="tag"
@click="handleTagClick(tag)"
>
{{ tag.name }}
</span>
</div>
</template>
数据绑定与交互逻辑
在 Vue 的 data 或 setup 中定义标签数据,并通过方法实现标签的增删或选中逻辑。

<script>
export default {
data() {
return {
tags: [
{ id: 1, name: 'Vue' },
{ id: 2, name: 'JavaScript' },
{ id: 3, name: '前端' }
]
};
},
methods: {
handleTagClick(tag) {
console.log('选中标签:', tag.name);
// 可扩展为选中状态切换或删除逻辑
}
}
};
</script>
样式设计与状态反馈
通过 CSS 为标签添加视觉反馈,如悬停效果、选中状态。使用 Vue 的 :class 动态切换样式类。

<style scoped>
.tag-container {
display: flex;
gap: 8px;
}
.tag {
padding: 4px 12px;
background: #e0e0e0;
border-radius: 16px;
cursor: pointer;
}
.tag:hover {
background: #d0d0d0;
}
.tag.active {
background: #42b983;
color: white;
}
</style>
动态添加/删除标签
扩展功能允许用户输入新标签或删除现有标签。结合 v-model 和数组操作实现。
<template>
<div>
<input v-model="newTag" @keyup.enter="addTag" placeholder="输入标签名" />
<div class="tag-container">
<span
v-for="tag in tags"
:key="tag.id"
class="tag"
@click="removeTag(tag.id)"
>
{{ tag.name }} ×
</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
newTag: '',
tags: [{ id: 1, name: '示例' }]
};
},
methods: {
addTag() {
if (this.newTag.trim()) {
this.tags.push({ id: Date.now(), name: this.newTag.trim() });
this.newTag = '';
}
},
removeTag(id) {
this.tags = this.tags.filter(tag => tag.id !== id);
}
}
};
</script>
使用第三方库增强功能
若需复杂功能(如拖拽排序),可集成 vue-draggable 等库。
npm install vue-draggable@next
<template>
<draggable v-model="tags" item-key="id">
<template #item="{ element }">
<span class="tag">{{ element.name }}</span>
</template>
</draggable>
</template>
<script>
import draggable from 'vuedraggable';
export default {
components: { draggable },
data() {
return { tags: [...] };
}
};
</script>






