效果如下:
1、新建一個tagsInput.vue組件
代碼如下:
<template>
<div class="tags_input">
<el-tag
v-for="(tag,index) in list"
:key="index"
closable
:disable-transitions="false"
@close="handleClose(tag)">
{{tag}}
</el-tag>
<el-input
type="text"
:placeholder="placeholder"
v-model="value"
@keyup.enter.native="add">
</el-input>
</div>
</template>
<script>
export default {
name:'TagsInput',
props: {
listFilter: Boolean, // 是否去重
defaulList: null, // 默認值
placeholder: null // 佔位文字
},
data() {
return {
value: '',
list: [],
}
},
mounted() {
this.list = this.defaulList
this.$emit('input', this.list) // 發送給父級的tagslist
},
methods: {
add() {
let self = this
if (self.value != '' || self.value != ' ') {
self.list.push(self.value)
if (self.listFilter) {
let arr = self.list
let set = new Set(arr)
self.list = Array.from(set)
}
}
self.value = ''
self.$emit('input', self.list)
},
handleClose(tag) {
let self = this
self.$emit('tagClose', tag)
self.list.splice(self.list.indexOf(tag), 1);
},
}
}
</script>
2、組件的使用
建一個demo.vue頁面,使用tagsInput組件
<template>
<div>
<div class="com-dialog-s-title">FrosTagsInput組件</div>
<div style="width: 500px">
<tags-input
v-model="tagList"
:defaulList="defaulList"
:listFilter=true
placeholder="按enter鍵創建標籤"
@tagClose="tagClose"></tags-input>
</div>
</div>
</template>
<script>
import TagsInput from 'src/components/tagsInput'
export default {
components: {
TagsInput
},
data() {
return {
// 子組件返回的list
tagList: null,
// 付默認值
defaulList:['標籤一','標籤二'],
// 是否去重
listFilter:false
}
},
methods: {
// 標籤關閉方法
tagClose(tag){
console.log(tag)
}
}
}
</script>