//引入:Tap 标签
import Tap from '@/components/Tap/index.vue'
//使用:
<Tap :tapList="tapList" :canDouble="true"></Tap>
//标签 初始列表:
const tapList=['Tag 1', 'Tag 2', 'Tag 3']
//canDouble 标签是否可以重复: Boolean型
:canDouble="true"
index.vue:
<script setup>
import { ref,nextTick } from 'vue';
import { ElMessage } from 'element-plus'
const props=defineProps({
tapList:Array,
canDouble:Boolean
})
//标签列表
const tapListNew=ref(props.tapList)
//展示标签还是输入框:
const isAdd=ref(true)
const inputAuto=ref() //输入框的引用
//输入框内容:
const inputC=ref('')
//点击添加新标签按钮:
const clickNewTag=()=>{
isAdd.value=false
//nextTick(dom更新完毕后)
nextTick(()=>{
inputAuto.value.focus() //input输入框 显示后立马聚焦
})
}
//输入框失焦:
const inputBlur=()=>{
isAdd.value=true
//判断是否已存在
let ishad=tapListNew.value.some(item=>item===inputC.value)
if(inputC.value!==''){
if(props.canDouble){
//标签可重复
tapListNew.value.push(inputC.value)
}else{
//标签不可重复
if(ishad){
//输入内容 已 存在
ElMessage.warning(`“${inputC.value}”已存在`)
}else{
//输入内容 不 存在
tapListNew.value.push(inputC.value)
}
}
}
inputC.value=''
}
//按下回车:
const keydownEnter=()=>{
inputBlur()
}
//点击删除:
const remove=(val)=>{
tapListNew.value=tapListNew.value.filter(item=>item!==val)
}
</script>
<template>
<div class="main">
<span class="tap" v-for="(item,index) in tapListNew" :key="index">
{{ item }}
<button @click="remove(item)">x</button>
</span>
<span class="addTap" v-if="isAdd" @click="clickNewTag">+ New Tag</span>
<input type="text" v-else @blur="inputBlur" ref="inputAuto" v-model="inputC" @keydown.enter="keydownEnter">
</div>
</template>
<style scoped lang="scss">
.main{
span{
display: inline-block;
height: 25px;
line-height: 25px;
padding-left: 10px;
padding-right: 10px;
margin-left: 10px;
border-radius: 5px;
font-size: 15px;
}
.tap{
border: 1px solid rgb(135, 147, 199);
background-color: rgb(207, 227, 235);
button{
background-color:rgb(0, 0, 0,0);
border: none;
cursor:pointer;
height: 25px;
line-height: 25px;
font-size: 18px;
}
}
.addTap{
border: 1px solid rgb(227, 212, 212);
}
input{
height: 25px;
line-height: 25px;
padding-left: 10px;
padding-right: 10px;
margin-left: 10px;
border-radius: 5px;
font-size: 15px;
border: 1px solid rgb(227, 212, 212);
}
}
</style>