本篇博客内容采用ant-design的标签进行实现(类似组件库的tag组件类似使用)
目录
实现效果:
关键变量
keywords: [], //关联词列表
checkArray: [], //关键词选中列表 选中为true
tags: [], //搜索tag列表
待选标签列表
<a-checkable-tag
@change="handleChange(i)"
v-for="(p, i) in keywords"
:key="i"
v-model="checkArray[i]"
style="font-family: ZZGF; font-size: 15px; margin-bottom: 10px; font-weight: bolder"
>{{p}}</a-checkable-tag>
handleChange(index){
// 限定最多选择10个关键词进行搜索
if (this.tags.length === 10 && this.tags.indexOf(this.keywords[index]) === -1){
this.$message.warn({ content: '最多使用10个关键词进行搜索',
icon: () =>
this.$createElement("a-icon", {
props: {
type: "stop"
}
}),
top: '100px',
duration: 2
});
this.checkArray[index] = false
}
else {
// 选择
if (this.tags.indexOf(this.keywords[index]) === -1){
this.tags.push(this.keywords[index])
}
// 取消选择
else{
this.checkArray[index] = false
this.tags.splice(this.tags.indexOf(this.keywords[index]), 1)
}
}
},
搜索(已选择)tag列表
<div>
<template v-for="(tag, index) in tags">
<a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
<a-tag :key="tag"
:closable="true"
@close="() => handleClose(tag)"
style="font-family: ZZGF; font-size: 15px; margin-bottom: 10px; font-weight: bolder">
{{ `${tag.slice(0, 20)}...` }}
</a-tag>
</a-tooltip>
<a-tag v-else :key="tag"
:closable="true"
@close="() => handleClose(tag)"
style="font-family: ZZGF; font-size: 15px; margin-bottom: 10px; font-weight: bolder">
{{ tag }}
</a-tag>
</template>
// 自定义标签输入
<a-input
v-if="inputVisible"
ref="input"
type="text"
@keydown.native="keydown($event)" //不允许空格输入
size="small"
style="font-family: ZZGF"
:style="{ width: '78px' }"
:value="inputValue"
@change="handleInputChange"
@blur="handleInputConfirm"
@keyup.enter="handleInputConfirm"
/>
<a-tag v-else
style="background: #fff; borderStyle: dashed; font-family: ZZGF; font-size: 15px; margin-bottom: 10px; font-weight: bolder"
@click="showInput">
<a-icon type="plus" /> 自定义关键词
</a-tag>
</div>
从搜索tag列表取消某一标签
handleClose(removedTag) {
const tags = this.tags.filter(tag => tag !== removedTag);
// console.log(tags);
if (this.keywords.indexOf(removedTag) !== -1)
this.checkArray[this.keywords.indexOf(removedTag)] = false
this.tags = tags;
},
自定义关键词确认添加(限定数量10)
handleInputConfirm() {
const inputValue = this.inputValue;
let tags = this.tags;
if (inputValue && tags.indexOf(inputValue) === -1 && inputValue.split(" ").join("").length !== 0) {
tags = [...tags, inputValue];
}
// console.log(tags);
Object.assign(this, {
tags,
inputVisible: false,
inputValue: '',
});
},
确认添加成功后回调
注意,若自定义添加了某关键词正好与待选列表中某个关键词相同,则令待选列表中关键词为选中状态。
handleInputChange(e) {
if (this.tags.length === 10){
this.$message.warn({ content: '最多使用10个关键词进行搜索',
icon: () =>
this.$createElement("a-icon", {
props: {
type: "stop"
}
}),
top: '100px',
duration: 2
});
return
}
if (this.keywords.indexOf(e.target.value) !== -1)
this.checkArray[this.keywords.indexOf(e.target.value)] = true
this.inputValue = e.target.value;
},