vue实现tag
Vue 实现标签(Tag)功能
在 Vue 中实现标签(Tag)功能可以通过多种方式完成,以下是一些常见的方法和实现步骤:
使用动态组件和 v-for
通过 v-for 指令动态渲染标签列表,结合样式和交互逻辑实现标签功能。

<template>
<div class="tag-container">
<span
v-for="(tag, index) in tags"
:key="index"
class="tag"
@click="removeTag(index)"
>
{{ tag }}
<span class="close-icon">×</span>
</span>
<input
v-model="newTag"
@keydown.enter="addTag"
placeholder="输入标签并按回车"
>
</div>
</template>
<script>
export default {
data() {
return {
tags: ['Vue', 'JavaScript', '前端'],
newTag: ''
}
},
methods: {
addTag() {
if (this.newTag.trim() && !this.tags.includes(this.newTag.trim())) {
this.tags.push(this.newTag.trim());
this.newTag = '';
}
},
removeTag(index) {
this.tags.splice(index, 1);
}
}
}
</script>
<style>
.tag-container {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
.tag {
background-color: #e0e0e0;
padding: 4px 8px;
border-radius: 4px;
display: inline-flex;
align-items: center;
cursor: pointer;
}
.close-icon {
margin-left: 4px;
}
input {
border: none;
outline: none;
flex-grow: 1;
}
</style>
使用第三方组件库
许多 Vue 组件库(如 Element UI、Ant Design Vue)提供了现成的 Tag 组件,可以直接使用。

以 Element UI 为例:
<template>
<div>
<el-tag
v-for="(tag, index) in tags"
:key="index"
closable
@close="removeTag(index)"
>
{{ tag }}
</el-tag>
<el-input
v-model="newTag"
@keydown.enter.native="addTag"
placeholder="输入标签并按回车"
/>
</div>
</template>
<script>
export default {
data() {
return {
tags: ['Element', 'Vue', 'UI'],
newTag: ''
}
},
methods: {
addTag() {
if (this.newTag.trim() && !this.tags.includes(this.newTag.trim())) {
this.tags.push(this.newTag.trim());
this.newTag = '';
}
},
removeTag(index) {
this.tags.splice(index, 1);
}
}
}
</script>
实现可编辑标签
通过动态切换显示模式(查看/编辑)实现标签的编辑功能。
<template>
<div class="editable-tags">
<div
v-for="(tag, index) in tags"
:key="index"
class="tag-wrapper"
>
<span
v-if="!tag.editing"
class="tag"
@dblclick="editTag(index)"
>
{{ tag.text }}
<span class="close-icon" @click="removeTag(index)">×</span>
</span>
<input
v-else
v-model="tag.text"
@blur="saveTag(index)"
@keydown.enter="saveTag(index)"
v-focus
/>
</div>
<input
v-model="newTag"
@keydown.enter="addTag"
placeholder="输入标签并按回车"
>
</div>
</template>
<script>
export default {
directives: {
focus: {
inserted(el) {
el.focus();
}
}
},
data() {
return {
tags: [
{ text: '可编辑', editing: false },
{ text: '标签', editing: false }
],
newTag: ''
}
},
methods: {
addTag() {
if (this.newTag.trim() && !this.tags.some(t => t.text === this.newTag.trim())) {
this.tags.push({ text: this.newTag.trim(), editing: false });
this.newTag = '';
}
},
removeTag(index) {
this.tags.splice(index, 1);
},
editTag(index) {
this.tags[index].editing = true;
},
saveTag(index) {
this.tags[index].editing = false;
}
}
}
</script>
注意事项
- 标签的唯一性可以通过检查数组是否已存在相同标签来保证
- 动态添加标签时需处理输入验证和空值情况
- 删除标签时需确保索引正确
- 可编辑标签需处理焦点和失焦事件
以上方法可以根据实际需求进行调整和扩展,例如添加动画效果、颜色分类或与其他表单组件联动。






