vue实现tag效果
Vue 实现 Tag 标签效果
在 Vue 中实现 Tag 标签效果可以通过多种方式完成,以下是一些常见的方法和实现步骤。
使用原生 HTML 和 CSS
通过简单的 HTML 结构和 CSS 样式,可以快速实现基础的 Tag 效果。
<template>
<div class="tag-container">
<span class="tag" v-for="tag in tags" :key="tag">{{ tag }}</span>
</div>
</template>
<script>
export default {
data() {
return {
tags: ['Vue', 'JavaScript', 'CSS', 'HTML']
}
}
}
</script>
<style>
.tag-container {
display: flex;
gap: 8px;
}
.tag {
padding: 4px 8px;
background-color: #e0e0e0;
border-radius: 4px;
font-size: 14px;
}
</style>
使用组件库
许多流行的 Vue 组件库(如 Element UI、Ant Design Vue)提供了现成的 Tag 组件。
以 Element UI 为例:
<template>
<el-tag v-for="tag in tags" :key="tag" type="success">{{ tag }}</el-tag>
</template>
<script>
export default {
data() {
return {
tags: ['Vue', 'JavaScript', 'CSS', 'HTML']
}
}
}
</script>
动态添加和删除 Tag
通过绑定事件和方法,可以实现动态添加和删除 Tag 的功能。
<template>
<div>
<input v-model="newTag" @keyup.enter="addTag" placeholder="输入标签后按回车" />
<div class="tag-container">
<span class="tag" v-for="(tag, index) in tags" :key="index">
{{ tag }}
<button @click="removeTag(index)">×</button>
</span>
</div>
</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;
gap: 8px;
margin-top: 8px;
}
.tag {
padding: 4px 8px;
background-color: #e0e0e0;
border-radius: 4px;
font-size: 14px;
}
button {
background: none;
border: none;
cursor: pointer;
}
</style>
自定义 Tag 组件
如果需要更复杂的 Tag 功能,可以封装一个自定义的 Tag 组件。
<!-- Tag.vue -->
<template>
<span class="custom-tag" :style="{ backgroundColor: color }">
<slot></slot>
<span class="close-btn" @click="$emit('close')">×</span>
</span>
</template>
<script>
export default {
props: {
color: {
type: String,
default: '#e0e0e0'
}
}
}
</script>
<style>
.custom-tag {
padding: 4px 8px;
border-radius: 4px;
font-size: 14px;
display: inline-flex;
align-items: center;
}
.close-btn {
margin-left: 4px;
cursor: pointer;
}
</style>
在父组件中使用:

<template>
<div>
<Tag v-for="(tag, index) in tags" :key="index" @close="removeTag(index)">
{{ tag }}
</Tag>
</div>
</template>
<script>
import Tag from './Tag.vue';
export default {
components: { Tag },
data() {
return {
tags: ['Vue', 'JavaScript', 'CSS', 'HTML']
}
},
methods: {
removeTag(index) {
this.tags.splice(index, 1);
}
}
}
</script>
以上方法可以根据具体需求选择使用,灵活调整样式和功能。






