vue 实现tag标签
Vue 实现 Tag 标签
在 Vue 中实现 Tag 标签可以通过多种方式完成,以下是几种常见的实现方法。
使用原生 HTML 和 CSS
通过 Vue 的模板语法结合 CSS 样式可以快速实现基础的 Tag 标签。

<template>
<div class="tag-container">
<span v-for="tag in tags" :key="tag" class="tag">{{ tag }}</span>
</div>
</template>
<script>
export default {
data() {
return {
tags: ['Vue', 'JavaScript', 'HTML', 'CSS']
}
}
}
</script>
<style>
.tag {
display: inline-block;
padding: 4px 8px;
margin: 4px;
background-color: #f0f0f0;
border-radius: 4px;
font-size: 14px;
}
</style>
使用组件封装
将 Tag 封装为可复用的组件,增加灵活性和可定制性。

<!-- Tag.vue -->
<template>
<span class="tag" :style="{ backgroundColor: color }">
{{ text }}
<span v-if="closable" class="close" @click="$emit('close')">×</span>
</span>
</template>
<script>
export default {
props: {
text: String,
color: {
type: String,
default: '#f0f0f0'
},
closable: {
type: Boolean,
default: false
}
}
}
</script>
<style>
.tag {
display: inline-block;
padding: 4px 8px;
margin: 4px;
border-radius: 4px;
font-size: 14px;
}
.close {
margin-left: 4px;
cursor: pointer;
}
</style>
使用第三方库
可以借助第三方库如 element-ui 或 ant-design-vue 快速实现功能丰富的 Tag 标签。
<template>
<div>
<el-tag
v-for="tag in tags"
:key="tag"
closable
@close="handleClose(tag)"
>
{{ tag }}
</el-tag>
</div>
</template>
<script>
import { ElTag } from 'element-ui'
export default {
components: {
ElTag
},
data() {
return {
tags: ['Vue', 'JavaScript', 'HTML', 'CSS']
}
},
methods: {
handleClose(tag) {
this.tags = this.tags.filter(t => t !== tag)
}
}
}
</script>
动态添加和删除 Tag
实现动态添加和删除 Tag 的功能,增强交互性。
<template>
<div>
<input
v-model="newTag"
@keyup.enter="addTag"
placeholder="输入标签后按回车"
/>
<div class="tag-container">
<span
v-for="tag in tags"
:key="tag"
class="tag"
@click="removeTag(tag)"
>
{{ tag }} ×
</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tags: ['Vue', 'JavaScript'],
newTag: ''
}
},
methods: {
addTag() {
if (this.newTag.trim() && !this.tags.includes(this.newTag)) {
this.tags.push(this.newTag.trim())
this.newTag = ''
}
},
removeTag(tag) {
this.tags = this.tags.filter(t => t !== tag)
}
}
}
</script>
通过以上方法,可以根据需求灵活实现 Vue 中的 Tag 标签功能。






