避免在input框中输入通过","分割的字符串。通过手动添加的方式进行配置。降低配置失败的概率
效果图
一:使用方式
<el-form-item label="简称" prop="id" :class="reviewList.cooperatorId">
<!-- 为了让前端提示错误信息 -->
<el-input v-model="ruleForm.cooperatorId" v-show="false"></el-input>
<el-dynamic-tags v-model="ruleForm.id" :updateValue="id" :closable="!isDisabled"
placeholder="请输入简称"></el-dynamic-tags>
</el-form-item>
二:创建公共组件
<template>
<div>
<el-container>
<el-aside>
<el-tag
:key="tag"
effect="plain"
:closable="closable"
v-for="tag in dynamicValue"
:style="closable?'':{'color':'#c0c4cc','background-color':'#F5F7FA'}"
:disable-transitions="disableTransitions"
@close="handleClose(tag)">
{{ tag }}
</el-tag>
<el-input
class="input-new-tag"
v-if="inputVisible"
v-model.trim="inputValue"
ref="saveTagInput"
size="small"
:autofocus="true"
@keyup.enter.native="handleInputConfirm"
@blur="handleInputConfirm"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput"> ✚ </el-button>
</el-aside>
</el-container>
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
defalut: ''
},
disableTransitions: {
type: Boolean,
defalut: false
},
closable: {
type: Boolean,
defalut: true,
require: false
},
updateValue: {
type: Function,
require: true
}
},
data() {
return {
updateCount: 0,
dynamicValue: [],
inputVisible: false,
inputValue: ''
};
},
mounted() {
// 这样写的目的是为了只watch一次,因为网络原因导致value 的值没有实时同步过来.用mounted.watch代替created
const unwatch = this.$watch('value', function (newValue, oldValue) {
this.dynamicValue = newValue.split(",");
unwatch();
});
},
watch: {
'dynamicValue'(newData) {
// 回调父组件方法,更新变量
this.updateValue(this.dynamicValue.join(","));
}
},
methods: {
handleClose(tag) {
this.dynamicValue.splice(this.dynamicValue.indexOf(tag), 1);
},
showInput() {
this.inputVisible = true;
this.$nextTick(_ => {
this.$refs.saveTagInput.$refs.input.focus();
});
},
handleInputConfirm() {
let inputValue = this.inputValue;
let existence = this.dynamicValue.includes(inputValue);
if (existence) {
this.$message.error("存在相同的值,请检查后重新输入");
} else {
if (inputValue) {
this.dynamicValue.push(inputValue);
}
}
this.inputVisible = false;
this.inputValue = '';
}
}
}
</script>
<style scoped>
.el-tag + .el-tag {
margin-right: 3px;
}
.el-tag--plain {
background-color: #fff;
border-color: #dcdfe6;
color: #606266;
margin-right: 3px;
margin-bottom: 3px;
}
.el-tag--plain .el-tag__close {
color: #606266;
}
.button-new-tag {
margin-right: 5px;
height: 32px;
line-height: 30px;
padding-top: 0;
padding-bottom: 0;
}
.input-new-tag {
width: 100%;
/*margin-left: 10px;*/
vertical-align: bottom;
}
</style>
三:注册成全局组件
main.js 文件
import ElDynamicTags from '@/components/common/elDynamicTags' // - 动态输入框
Vue.component('ElDynamicTags', ElDynamicTags);