Tags-Input
实现要求
- 使用input和tags能够输入回车后显示
- 支持校验是否填写
代码
<template>
<div>
<template v-for="(tag,index) in tags">
<a-tag
:style="TgOptions.tagStyle"
:key="index"
:closable="closable"
@close="() => handleClose(tag)"
>{{ tag.value }}</a-tag>
</template>
<span v-if="tags.length != max">
<a-input
v-if="inputVisible"
ref="input"
type="text"
size="small"
:style="TgOptions.style"
:value="inputValue"
:placeholder="TgOptions.placeholder"
@change="handleInputChange"
@blur="(e)=>handleInputConfirm(e,'blur')"
@keyup.enter.stop="(e)=>handleInputConfirm(e,'keyup')"
/>
<a-tag v-else style="background: #fff; borderStyle: dashed;" @click="showInput">
<a-icon type="plus" />
{{TgOptions.title}}
</a-tag>
</span>
</div>
</template>
<script>
export default {
model: {
prop: "value",
event: "change"
},
data() {
return {
tags: [],
inputVisible: false,
inputValue: "",
data: [{
name: "1",
value: "第一个选项"
}]
};
},
mounted() {
// 回显赋值需要
this.$watch("value", function(newValue, oldValue) {
let arr = newValue ? newValue.split(",") : [];
let resultArr = [];
for (let i = 0; i < arr.length; i++) {
// alert(arr[i]);
resultArr.push({
value: arr[i]
});
}
this.tags = resultArr;
});
},
name: "tags-input",
props: {
value: {
type: String
// 这个参数是v-decorator给子组件传值用的
// 这里不要给默认值, 在form下使用会爆警告 Warning: SquareUpload `default value` can not collect, please use `option.initialValue` to set default value.
},
max: {
type: Number,
default: 999999
},
closable: {
type: Boolean,
default: true
},
TgOptions: {
type: Object,
default: function() {
return {
title: "添加tags", // 添加title,
placeholder: "请输入信息",
style: {
// input style
width: "180px"
},
tagStyle: {}
};
}
}
},
methods: {
dataChange() {
let data = this.tags;
let result = [];
for (let i = 0; i < data.length; i++) {
result.push(data[i].value);
}
this.$emit("change", result.join(","));
},
handleClose(removedTag) {
const tags = this.tags.filter(tag => tag !== removedTag);
this.tags = tags;
this.dataChange();
this.$emit("handleChange", tags, this.tags);
},
showInput() {
this.inputVisible = true;
this.$nextTick(function() {
this.$refs.input.focus();
});
},
handleInputChange(e) {
this.inputValue = e.target.value;
},
handleInputConfirm(e, type) {
if (this.inputValue == "" || !this.inputValue) {
if (type === "blur") {
this.inputVisible = false;
}
return false;
}
let data = this.data.filter(res => res.name == this.inputValue);
if (data[0]) {
const inputValue = {
value: this.inputValue + "/" + data[0]
};
let tags = this.tags;
tags = [...tags, inputValue];
Object.assign(this, {
tags,
inputVisible: false,
inputValue: ""
});
this.dataChange();
} else {
this.$message.info("只能维护存在的人员");
this.inputVisible = false;
this.inputValue = "";
}
}
}
};
</script>
<style>
</style>
<tags-input
:TgOptions="{title:'添加相关人员'}"
:max='3'
v-decorator="['values',{rules: [{ required: true, message: $t('请选择')+$t('相关人员') }],validateTrigger: ['change']}]">
</tags-input>
效果