代码直接CV即可,后期更新el-input使用
<template>
<div class="contaion" @click="onclick">
<!-- 生成的标签 -->
<div v-for="(item, index) in AllTags" :key="index" class="spanbox">
<span class="tagspan">{{ item }}</span>
<i class="iClose" @click="removeTag(item,index)"></i>
</div>
<!-- 输入框 -->
<input
placeholder="输入后按<回车>创建"
v-model="inputValue"
@keyup.enter="addTags"
:style="inputStyle"
class="inputTag"
ref="inputTag"
type="text"
/>
</div>
</template>
<script>
export default {
data() {
return {
//输入框
inputValue: "",
//tag
AllTags: ["标签1", "标签2"],
//输入框宽度
inputLength: "",
//计算删除位置
n: 0,
};
},
watch: {
//监听输入的值越多,输入框越长
inputValue(val) {
// 实时改变input输入框宽度,防止输入内容超出input默认宽度显示不全
this.inputLength = this.$refs.inputTag.value.length * 12 + 50;
}
},
computed: {
//计算属性:计算出动态输入框宽度
inputStyle() {
let style = {};
style.width = `${this.inputLength}px`;
return style;
}
},
created(){
console.log(this.AllTags)
},
methods: {
//点击叉叉删除tag
removeTag(item,index) {
this.AllTags.splice(index, 1);
console.log(this.AllTags)
},
//回车增加tag
addTags() {
//新增函数中可以加一些你所需要的校验规则。比如只能是数子,或者不能输入‘,’等
if (this.inputValue) {
//添加tag
this.AllTags.push(this.inputValue);
//清空输入框
this.inputValue = "";
}
},
//点击父盒子输入框获取焦点
onclick() {
this.$nextTick(() => {
this.$refs.inputTag.focus();
})
}
}
};
</script>
<style scoped>
.contaion {
width: 600px;
box-sizing: border-box;
background-color: white;
border: 1px solid #409EFF;
border-radius: 4px;
font-size: 12px;
text-align: left;
padding-left: 5px;
word-wrap: break-word;
overflow: hidden;
}
/* 标签 */
.spanbox {
display: inline-block;
font-size: 14px;
margin: 3px 4px 3px 0;
background-color: #ecf5ff;
border: 1px solid #e8eaec;
border-radius: 3px;
box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}
/* 标签文字 */
.tagspan {
height: 24px;
line-height: 22px;
max-width: 99%;
position: relative;
display: inline-block;
padding-left: 8px;
color: #409EFF;
font-size: 14px;
opacity: 1;
vertical-align: middle;
overflow: hidden;
transition: 0.25s linear;
}
/* tag的叉叉 */
.iClose {
padding: 0 6px 0 4px;
opacity: 1;
-webkit-filter: none;
filter: none;
color: #409EFF;
/* font-weight: 600; */
cursor:pointer;
}
/* 鼠标经过叉叉 */
.iClose:hover{
background-color: #409EFF;
border-radius: 50%;
color: #fff;
}
.iClose:after {
content: "\00D7";
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
/* line-height: 27px; */
transition: 0.3s, color 0s;
}
/* input */
.inputTag {
font-size: 16px;
border: none;
box-shadow: none;
outline: none;
background-color: transparent;
padding: 0;
width: auto;
min-width: 150px;
vertical-align: top;
height: 32px;
color: #495060;
line-height: 32px;
}
/* 输入框提示文字大小 */
input:placeholder-shown {
font-size: 0.6rem;
}
</style>