iview 采坑记录

645 阅读1分钟

1. iview的tree组件设置expand不生效

在使用ivew的tree组件时,数据是动态绑定的,控件如下:

        <Tree :data="audioData" :render="renderContent" @on-toggle-expand="toggleExpand">
        </Tree>

初始化数据代码如下:

    initTree() {
      this.audioData = [
        {
          title: '组件1',
          children: [
            {
              title: '话术-时间到',
              children: [
                {
                  title: '话术-时间到',
                }
              ]
            }
          ]
        },
        {
          title: '组件2',
          children: [
            {
              title: '话术-提前结束',
              children: [
                {
                  title: '话术-提前结束',
                }
              ]
            }
          ]          
        }
      ];
    },

设置树形结构展开还是收起状态代码如下:

    //展开或合并树,当flag为true时全部展开,flag为false时全部合并
    exchangeTree(flag) {
      this.audioData = this.treeChangeExpand(this.audioData, flag);
    },
    //递归给树设置expand
    treeChangeExpand(treeData, flag) {
      let _this = this;
      for (var i = 0; treeData && i < treeData.length; i++) {
        treeData[i].expand = flag;
        if (treeData[i].children) {
          treeData[i].children = _this.treeChangeExpand(treeData[i].children,flag);
        }
      }
      return treeData;

测试发现并不生效。

对比发现,不调用上述自己写的treeChangeExpand方法设置expand,而是在初始化的时候就直接在treeData中写expand,如下:

     initTree() {
      this.audioData = [
        {
          title: '组件1',
          expand: true,
          children: [
            {
              title: '话术-时间到',
              children: [
                {
                  title: '话术-时间到',
                }
              ]
            }
          ]
        },
        {
          title: '组件2',
          expand: true,
          children: [
            {
              title: '话术-提前结束',
              children: [
                {
                  title: '话术-提前结束',
                }
              ]
            }
          ]          
        }
      ];
    },

console.log(this.audioData),结果有expand并且有expand的get和set方法,如下,

而调用上述treeChangeExpand方法添加expand以后,打印出来的结果中有expand但没有expand的get和set方法。如下:

发现原来vue直接在json数据中添加属性是不行的,无法生成get和set方法,而需要使用vue的set方法。

将上述的treeChangeExpand方法改为如下,问题解决:

 treeChangeExpand(treeData, flag) {
      let _this = this;
      for (var i = 0; treeData && i < treeData.length; i++) {
        this.$set(treeData[i],'expand',flag); //重要!用set方法
        if (treeData[i].children) {
          treeData[i].children = _this.treeChangeExpand(treeData[i].children,flag);
        }
      }
      return treeData;
}