vue实现多标签选择
Vue 实现多标签选择
使用 v-model 和数组绑定
在 Vue 中,可以通过 v-model 绑定一个数组来实现多标签选择。适用于 checkbox 或自定义多选组件。
<template>
<div>
<label v-for="tag in availableTags" :key="tag">
<input type="checkbox" v-model="selectedTags" :value="tag">
{{ tag }}
</label>
<p>已选择: {{ selectedTags }}</p>
</div>
</template>
<script>
export default {
data() {
return {
availableTags: ['前端', '后端', '移动端', '数据库'],
selectedTags: []
}
}
}
</script>
使用第三方组件库
对于更复杂的需求,可以使用现成的 UI 库如 Element UI、Ant Design Vue 等提供的多选标签组件。

以 Element UI 为例:

<template>
<el-select v-model="selectedTags" multiple placeholder="请选择标签">
<el-option
v-for="tag in availableTags"
:key="tag"
:label="tag"
:value="tag">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
availableTags: ['Vue', 'React', 'Angular', 'Svelte'],
selectedTags: []
}
}
}
</script>
自定义标签选择组件
如果需要完全自定义的交互,可以封装一个标签选择组件:
<template>
<div class="tag-selector">
<div class="selected-tags">
<span v-for="(tag, index) in selectedTags" :key="index" class="tag">
{{ tag }}
<button @click="removeTag(index)">×</button>
</span>
</div>
<input
type="text"
v-model="newTag"
@keydown.enter="addTag"
placeholder="输入标签后按回车">
</div>
</template>
<script>
export default {
props: {
value: Array
},
data() {
return {
newTag: ''
}
},
computed: {
selectedTags: {
get() { return this.value },
set(val) { this.$emit('input', val) }
}
},
methods: {
addTag() {
if (this.newTag.trim() && !this.selectedTags.includes(this.newTag)) {
this.selectedTags = [...this.selectedTags, this.newTag.trim()]
this.newTag = ''
}
},
removeTag(index) {
this.selectedTags.splice(index, 1)
}
}
}
</script>
<style>
.tag {
display: inline-block;
margin: 0 5px 5px 0;
padding: 3px 8px;
background: #eee;
border-radius: 3px;
}
</style>
使用 Vuex 管理标签状态
对于全局共享的标签数据,可以结合 Vuex 管理:
// store.js
export default new Vuex.Store({
state: {
selectedTags: []
},
mutations: {
addTag(state, tag) {
if (!state.selectedTags.includes(tag)) {
state.selectedTags.push(tag)
}
},
removeTag(state, index) {
state.selectedTags.splice(index, 1)
}
}
})
<template>
<div>
<input
type="text"
v-model="newTag"
@keydown.enter="addTag">
<div v-for="(tag, index) in selectedTags" :key="index">
{{ tag }}
<button @click="removeTag(index)">删除</button>
</div>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
data() {
return {
newTag: ''
}
},
computed: {
...mapState(['selectedTags'])
},
methods: {
...mapMutations(['addTag', 'removeTag']),
addTag() {
if (this.newTag.trim()) {
this.$store.commit('addTag', this.newTag.trim())
this.newTag = ''
}
}
}
}
</script>






