vue实现tag效果
Vue 实现标签(Tag)效果的方法
基础标签组件实现
通过Vue组件封装可复用的标签样式,支持动态内容和自定义样式:

<template>
<span class="tag" :style="{ backgroundColor: color }">
{{ text }}
<span v-if="closable" class="close-icon" @click="$emit('close')">×</span>
</span>
</template>
<script>
export default {
props: {
text: String,
color: {
type: String,
default: '#409EFF'
},
closable: Boolean
}
}
</script>
<style scoped>
.tag {
display: inline-block;
padding: 0 8px;
height: 24px;
line-height: 24px;
border-radius: 4px;
color: white;
margin-right: 8px;
}
.close-icon {
margin-left: 4px;
cursor: pointer;
}
</style>
动态标签列表
结合v-for实现可增删的标签列表:

<template>
<div>
<div v-for="(tag, index) in tags" :key="index">
<Tag
:text="tag.text"
:color="tag.color"
:closable="true"
@close="removeTag(index)"
/>
</div>
<input
v-model="newTag"
@keyup.enter="addTag"
placeholder="输入标签后按回车"
/>
</div>
</template>
<script>
import Tag from './Tag.vue'
export default {
components: { Tag },
data() {
return {
tags: [
{ text: 'Vue', color: '#42b983' },
{ text: 'JavaScript', color: '#f1c40f' }
],
newTag: ''
}
},
methods: {
addTag() {
if (this.newTag.trim()) {
this.tags.push({
text: this.newTag,
color: `#${Math.floor(Math.random()*16777215).toString(16)}`
})
this.newTag = ''
}
},
removeTag(index) {
this.tags.splice(index, 1)
}
}
}
</script>
第三方库实现
使用成熟的UI库如Element UI的Tag组件:
<template>
<el-tag
v-for="tag in dynamicTags"
:key="tag"
closable
:type="tag.type"
@close="handleClose(tag)">
{{ tag.name }}
</el-tag>
</template>
<script>
export default {
data() {
return {
dynamicTags: [
{ name: '标签一', type: '' },
{ name: '标签二', type: 'success' }
]
}
},
methods: {
handleClose(tag) {
this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
}
}
}
</script>
动画效果增强
为标签添加过渡动画:
<template>
<transition-group name="tag-list" tag="div">
<Tag
v-for="tag in tags"
:key="tag.id"
:text="tag.text"
@close="removeTag(tag.id)"
/>
</transition-group>
</template>
<style>
.tag-list-move {
transition: transform 0.3s;
}
.tag-list-enter-active,
.tag-list-leave-active {
transition: opacity 0.3s;
}
.tag-list-enter,
.tag-list-leave-to {
opacity: 0;
}
</style>






