需求:做一个添加标签的功能,点击添加后输入内容后回车可以添加,并且标签可以删除
鼠标按下后触发handleLabel函数,根据回车的keycode判断用户是不是按下的回车键,回车键键值为13,用户按下回车键后把输入的内容添加到标签中,并且清空输入框内容,如果用户输入为空那么会给用户提示。
@keyup.enter.native="handleLabel"
handleLabel(key) {
if (key.keyCode == 13) {
if (this.labelValue) {
this.labelFlag = false;
this.label.push({ name: this.labelValue });
this.$nextTick(() => (this.labelValue = ''));
} else {
this.$message.warning('请输入标签内容');
}
}
},
<!--
* @Descripttion: vue使用el-tag完成添加标签操作
* @Author: 叫我欧皇大人
* @email: 13071200550@163.com
* @Date: 2023-12-15
-->
<template>
<div class="content-box">
<div class="container">
<el-tag v-for="(item, index) in label" :key="index" closable @close="label.splice(index, 1)" style="margin: 0 10px">{{
item.name
}}</el-tag>
<el-input
style="width: 150px"
placeholder="请输入标签"
size="small"
clearable
v-model="labelValue"
@keyup.enter.native="handleLabel"
v-if="labelFlag == true"
></el-input>
<el-button v-else type="primary" size="small" icon="el-icon-plus" @click="addLabel()">添加标签</el-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
label: [{ name: '前端' }],
labelValue: '',
labelFlag: false
};
},
mounted() {},
methods: {
handleLabel(key) {
if (key.keyCode == 13) {
if (this.labelValue) {
this.labelFlag = false;
this.label.push({ name: this.labelValue });
this.$nextTick(() => (this.labelValue = ''));
} else {
this.$message.warning('请输入标签内容');
}
}
},
addLabel() {
this.labelFlag = true;
}
}
};
</script>
<style lang="scss" scoped>
.content-box {
.container {
// height: 400px;
display: flex;
}
}
.el-select {
width: 80px;
}
</style>
文章到此结束,希望对你有所帮助~~