原创

view框架中tag标签不可编辑的解决办法

温馨提示:
本文最后更新于 2022年11月02日,已超过 720 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

需求:view 框架中的 tag标签,不可编辑,并想要自定义标签的内容

遇到的问题:

    1 view框架中tag标签不可编辑

       解决方法:自己实现ivew的tag,设置span 标签的 contenteditable="true",并且实现标签的新增和删除

   2  vue 中获取焦点的方法不可用

      解决方法:自定义focus的指令,在需要使用的标签内,添加v-focus

   3 span标签没有change事件,如何监听span标签中的内容的改变。
      解决方法:给span标签添加tabindex属性

    

 <span  v-on:blur= handleSpan($event,item) tabindex="0" hidefocus="true"  contenteditable="true" style="hight:12px;outline=0"  class="ivu-tag-text">{
  { item }}</span> 

     可以参考大佬的这边文章,写的比较详细https://blog.csdn.net/heng_yan/article/details/80347298

    html 代码如下

vue 需要自定义获取焦点事件,directives和mounted 是同级别的位置

directives: {
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus()
    }
  }
}

directives和mounted 是同级别的位置如下图

在需要获取焦点的标签内 添加上v-focus 属性,如

定义 如下变量

countTags: ['Java', 'dashuju'],//标签
inputVisible: false,
inputValue: '',

相关函数如下

//span标签里内容改变时的处理逻辑
     handleSpan(event,item){
      let spanValue = event.currentTarget.innerHTML
      if(item == spanValue){//span内容没有
        return
      }else{
        let index = this.countTags.indexOf(item);
        this.countTags.splice(index, 1);//删除原来的元素
         if (spanValue && this.countTags.indexOf(spanValue) == -1) {
             this.countTags.splice(index,0,spanValue);   //简简单单,push一下
        }
      }
    },
    //删除标签
    handleClose(tag) {
        this.countTags.splice(this.countTags.indexOf(tag), 1);
     },
     //一个回车事件,一个元素失去焦点时所触发的事件,触发同一个事件。
     handleInputConfirm() {
        let inputValue = this.inputValue.trim();
        if (inputValue && this.countTags.indexOf(inputValue) == -1) {
        this.countTags.push(inputValue);   //简简单单,push一下
        }
       this.inputVisible = false;
        this.inputValue = '';
        console.info(this.countTags);
     },
 
     showInput() {
      this.inputVisible = true;
      //  var saveTagInput = document.getElementsByName("saveTagInput")[0].focus();
      //  console.info(saveTagInput);
       this.$nextTick(() => {
        //  alert(this.$refs['saveTagInput']);
         this.$refs['saveTagInput'].focus();
       })

 

 

添加css样式

.input-new-tag {

width: 80px;

margin-left: 0px;

}

 

最终效果(忽略选择框):

   

    点击添加标签之后:

 

标签是可以编辑的

转载请注明出处,谢谢

 

 

正文到此结束
本文目录