思路:用一个大的div盒子包裹住已经生成的标签列表(遍历数组展示)和<input>标签,在<input>标签中回车键入一个,左侧的列表就多一个元素,<input>标签自动后移一段距离。
【标签结构】
<div id="father-box" style="width:600px;" @click="onclick">
<!-- 生成的标签,用ul li包裹也可以 -->
<div v-for="(item, index) in TagsAll" :key="index" class="span-box">
<div>{{ item }}</div>
<i class="el-icon-close" @click="removeTag(index, item)"></i>
</div>
<!-- 输入框:@keyup.delete="deleteTags"键盘删除标签 -->
<input
v-show="isShowInput"
placeholder="按回车键Enter创建标签 最多可添加5个标签"
v-model="currentval"
maxlength="10"
@keyup.enter="addTags"
class="input-tag"
ref="inputTag"
type="text"
/>
<span class="label-num">{{labelNum}}/5</span>
</div>
【script】
export default {
data(){
return{
TagsAll: [], // 标签数组
currentval: "", // 输入内容
isShowInput: true,
}
},
watch:{
// 监听标签数量,不得超过5个
TagsAll(value){
if ( value.length >= 3 ) this.$refs.inputTag.placeholder = '';
else this.$refs.inputTag.placeholder = '按回车键Enter创建标签 最多可添加5个标签';
if ( value.length >=5 ) this.isShowInput = false;
else this.isShowInput = true;
},
},
computed:{
// 显示已键入的标签个数
labelNum(){
return this.TagsAll.length;
},
},
methods:{
//点击父盒子输入框获取焦点
onclick() {
this.$nextTick(() => {
this.$refs.inputTag.focus();
});
},
// 回车键入标签
addTags() {
let that = this;
if ( this.currentval.trim() ) { // 输入有效内容
if ( this.currentval.trim().length > 6 ) { // 有效字符不能超过6个
this.$Message.destroy();
this.$Message.error('单标签长度不能超过6个字符!');
} else {
let sameList = this.TagsAll.filter((e)=>{
return e == that.currentval.trim();
})
if ( sameList.length != 0 ) {
this.$Message.destroy();
this.$Message.error('该标签已存在,请勿重复键入!');
} else {
this.TagsAll.push( this.currentval.trim() ); // 添加去除空格后的标签
}
this.currentval = ""; // 清空输入框
}
}
},
//点击叉叉删除tag
removeTag(index, item) {
this.articleLabelList.map((e)=>{
if ( item == e.name ) {
e.labelInTagsAll = false;
}
})
this.TagsAll.splice(index, 1);
},
}
}