vue实现tag标签
Vue 实现 Tag 标签的方法
在 Vue 中实现 Tag 标签可以通过多种方式完成,以下是几种常见的方法:
使用原生 HTML 和 CSS
通过 Vue 的模板语法和样式绑定,可以快速实现基础的 Tag 标签功能。
<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"
@keyup.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;
align-items: center;
}
.tag {
background: #e0e0e0;
padding: 4px 8px;
border-radius: 4px;
display: inline-flex;
align-items: center;
cursor: pointer;
}
.close-icon {
margin-left: 4px;
}
input {
border: 1px solid #ccc;
padding: 4px 8px;
border-radius: 4px;
}
</style>
使用第三方 UI 库
许多流行的 Vue UI 库提供了现成的 Tag 组件,例如 Element UI、Ant Design Vue 等。
以 Element UI 为例:
<template>
<el-tag
v-for="(tag, index) in tags"
:key="index"
closable
@close="removeTag(index)"
>
{{ tag }}
</el-tag>
<el-input
v-model="newTag"
placeholder="添加标签"
@keyup.enter.native="addTag"
/>
</template>
<script>
export default {
data() {
return {
tags: ['Vue', 'Element', '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>
实现可编辑的 Tag 标签
如果需要更复杂的交互,如双击编辑标签内容,可以扩展基础实现:
<template>
<div class="tag-container">
<span
v-for="(tag, index) in tags"
:key="index"
class="tag"
@dblclick="editTag(index)"
>
<span v-if="editingIndex !== index">{{ tag }}</span>
<input
v-else
v-model="tags[index]"
@blur="saveEdit"
@keyup.enter="saveEdit"
ref="editInput"
>
<span class="close-icon" @click="removeTag(index)">×</span>
</span>
<input
v-model="newTag"
@keyup.enter="addTag"
placeholder="添加标签"
>
</div>
</template>
<script>
export default {
data() {
return {
tags: ['可编辑', '标签'],
newTag: '',
editingIndex: -1
}
},
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);
},
editTag(index) {
this.editingIndex = index;
this.$nextTick(() => {
this.$refs.editInput[index].focus();
});
},
saveEdit() {
this.editingIndex = -1;
}
}
}
</script>
这些方法涵盖了从基础到进阶的 Tag 标签实现,可以根据项目需求选择适合的方式。







