一:样式
二:
2.1 对标签数组进行循环,根据数组变量editable来判断是输入框还是显示标签,当点击标签时和输入框失去焦点时,改变editable值。
2.2 最后一个标签,根据inputVisible的值判断是添加按钮还是输入框,同上,当点击按钮和输入框失去焦点时,改变inputVisible的值。
2.3 总结:就是一个循环+一个if-else判断,
三:代码
3.1 布局
<div class="inline-box">
<div v-for="(tag, index) in itemList" :key="index">
<el-input
class="input-new-tag"
v-if="editable[index]"
v-model="tag.tssName"
:ref="inputRef"
size="small"
placeholder="请输入条目"
@blur="handleEditableInputConfirm(tag, index)"
maxlength="20"
show-word-limit>
</el-input>
<el-tag v-else
@click="showEditTagInput(index)"
closable :disable-transitions="false"
@close="handleClose(tag, index)">
{{ tag.tssName }}
</el-tag>
</div>
<div>
<el-input
class="input-new-tag"
v-if="inputVisible"
v-model="inputValue"
ref="saveTagInput"
size="small"
@keyup.enter.native="handleInputConfirm"
@blur="handleInputConfirm"
maxlength="20"
show-word-limit>
</el-input>
<el-button
v-else
class="button-new-tag"
size="small"
@click="showInput">+ 新增条目</el-button>
</div>
</div>
3.2 变量
const inputValue = ref('')
const itemList = ref([])
const inputVisible = ref(false)
const saveTagInput = ref()
const editable = ref([])
const inputRef = ref()
3.3 函数
const handleEditableInputConfirm = (item, index) => {
if (item.tssName) {
editable.value[index] = false
} else {
ElMessage.error({ message: "请输入条目信息", type: "info" });
}
}
const showInput = () => {
inputVisible.value = true
nextTick(() => {
saveTagInput.value.input.focus()
})
}
const handleInputConfirm = () => {
if (inputValue.value) {
//标签数组数据,放入自己需要的
const str = {
tssName: inputValue.value,
value: itemList.value.length + 1,
projectId: route.params.id
}
itemList.value.push(str)
}
inputVisible.value = false
inputValue.value = ''
}
//编辑标签信息 input显示
const showEditTagInput = (index) => {
editable.value[index] = true
nextTick((_) => {
(inputRef.value && inputRef.value.input) ? inputRef.value.input.focus() : null;
});
}
//删除条目
const handleClose = (tag, index) => {
itemList.value.splice(index, 1);
}