>写在前面
在iview的文档中呢,提供了标签的动态使用 ——>点这里看iview标签,但它是不可编辑的,所以我写个文章记录一下,方便刚学习vue的小伙伴,直接使用,毕竟我开始也是不会到会。
首先,我给大家看一下我最初做的样子,我是写死的,然后进行点选。
这个效果不是我想要的
实现
iview 原生封装
<iv-tag
v-for="item in countTags"
:key="item"
:name="item"
closable
@on-close="handleClose">{{ item }}
</iv-tag >
//tag初始化参数
countTags: ['Java', 'Vue'],
实现方法
//标签部分
handleClose(tag) {
this.countTags.splice(this.countTags.indexOf(tag), 1);
},
注:iview中你使用tag,不是iv-tag,
如上代码段,遍历标签,不多解释,加了一个可关闭事件。参照iview中的官方文档,跟我这个大同小异。
动态标签实现
在iv-tag标签内写一个input。代码如下。
<iv-input
class="input-new-tag"
v-if="inputVisible"
v-model="inputValue"
ref="saveTagInput"
size="small"
@keyup.enter.native="handleInputConfirm"
@blur="handleInputConfirm"
>
//样式,写到你的style里
.input-new-tag {
width: 80px;
margin-left: 0px;
}
再加俩个初始参数,
inputVisible: false,
inputValue: '',
一个回车事件,一个元素失去焦点时所触发的事件,触发同一个事件。
handleInputConfirm() {
let inputValue = this.inputValue;
if (inputValue) {
this.countTags.push(inputValue);
}
this.inputVisible = false;
this.inputValue = '';
},
再在input下加一个button,使用ref引用上面的input,点击出现。
<iv-button v-else
size="small"
type="dashed"
icon="ios-add"
@click="showInput">+ 添加标签</iv-button>
showInput() {
this.inputVisible = true;
this.$nextTick(_ => {
this.$refs.saveTagInput.$refs.input.focus();
});
},
注意输入完成保存是回车保存。