vue实现tag标签
Vue 实现 Tag 标签
在 Vue 中实现 Tag 标签可以通过组件化的方式灵活定制样式和功能,以下是几种常见的实现方法:
基础实现
创建一个可复用的 Tag 组件,支持动态渲染标签内容和基础样式:
<template>
<span class="tag" :style="{ backgroundColor: color }">
{{ text }}
<span class="close" @click="$emit('close')">×</span>
</span>
</template>
<script>
export default {
props: {
text: String,
color: {
type: String,
default: '#409EFF'
}
}
}
</script>
<style scoped>
.tag {
display: inline-block;
padding: 2px 8px;
margin: 2px;
border-radius: 4px;
color: white;
font-size: 12px;
}
.close {
margin-left: 4px;
cursor: pointer;
}
</style>
动态标签列表
通过 v-for 渲染标签列表,并支持添加/删除操作:

<template>
<div>
<input v-model="newTag" @keyup.enter="addTag">
<div class="tag-container">
<tag
v-for="(tag, index) in tags"
:key="index"
:text="tag"
@close="removeTag(index)"
/>
</div>
</div>
</template>
<script>
import Tag from './Tag.vue'
export default {
components: { Tag },
data() {
return {
tags: ['Vue', 'JavaScript', 'CSS'],
newTag: ''
}
},
methods: {
addTag() {
if (this.newTag.trim()) {
this.tags.push(this.newTag.trim())
this.newTag = ''
}
},
removeTag(index) {
this.tags.splice(index, 1)
}
}
}
</script>
带可选择功能的标签
实现可选中状态的标签组件:
<template>
<span
class="tag"
:class="{ 'active': active }"
@click="$emit('update:active', !active)"
>
{{ text }}
</span>
</template>
<script>
export default {
props: {
text: String,
active: Boolean
}
}
</script>
<style scoped>
.tag {
display: inline-block;
padding: 4px 12px;
margin: 4px;
border: 1px solid #ddd;
border-radius: 16px;
cursor: pointer;
}
.tag.active {
background-color: #409EFF;
color: white;
border-color: #409EFF;
}
</style>
第三方库集成
使用现成的 UI 库快速实现标签功能:

-
Element UI:
<el-tag v-for="tag in tags" :key="tag" closable @close="handleClose(tag)" > {{ tag }} </el-tag> -
Ant Design Vue:
<a-tag v-for="tag in tags" :key="tag" closable @close="handleClose(tag)" > {{ tag }} </a-tag>
高级功能扩展
实现标签拖拽排序(需要配合 vuedraggable):
<draggable v-model="tags" tag="div" class="tag-container">
<tag
v-for="(tag, index) in tags"
:key="index"
:text="tag"
@close="removeTag(index)"
/>
</draggable>
import draggable from 'vuedraggable'
export default {
components: { draggable }
}






