文章开始前,说几句废话。
其实这个很简单,在iview的文档中呢,提供了标签的动态使用 ——>点这里看iview标签,但它是不可编辑的,所以我写个文章记录一下,方便刚学习vue的小伙伴,直接使用,毕竟我开始也是不会到会。
首先,我给大家看一下我最初做的样子,我是写死的,然后进行点选。。。
这个效果不是我想要的,最代码现在也是分享博客的时候,默认选择一些类别。当然具体情况具体分析。我想要的效果什么呢,比如csdn发表文章添加标签一样。虽然当时想是这么想的,但没有去深究,今天好好研究了一下,把这个写出来了。
接下来,我就给大家上代码,讲一下怎么实现。
<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,<Tag></Tag>,我这个是自定义引入,只使用我需要的iview插件。
如上代码段,遍历标签,不多解释,加了一个可关闭事件。参照iview中的官方文档,跟我这个大同小异。
接下来就是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); //简简单单,push一下
}
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();
});
},
至此,全文结束。
看一下效果~