用了ant-design-vue的tree,单个控件设置defaultExpandAll为true即可展开所有节点。在小demo里测试一点问题也没有。

<template>
  <a-tree
    :defaultExpandAll="true"
    :tree-data="treeData"
    :replace-fields="{
      children: 'children',
      title: 'title',
      key: 'id',
    }"
  />
</template>

<script>
export default {
  data() {
    return {
      treeData: [{"id":1,"title":"前端","children":[{"id":11,"title":"html"},{"id":12,"title":"css"},{"id":13,"title":"javascript"}]},{"id":2,"title":"后端","children":[{"id":21,"title":"php"},{"id":22,"title":"java"}]}],
    };
  }
};
</script>

然后放进项目,就不能如愿展开,经过一番测试之后,发现是因为treeDate数据是异步返回的。

分析了一下,应该是tree初始化成功,节点正常展开,后来数据再加载进来,也不会再次展开。

于是模拟了一下异步加载:

<template>
  <a-tree
    :expandedKeys="expandedKeys"
    :tree-data="treeData"
    :replace-fields="{
      children: 'children',
      title: 'title',
      key: 'id',
    }"
  />
</template>

<script>
export default {
  data() {
    return {
      treeData: [],
      expandedKeys: [1, 2],
    };
  },
  created(){
    setTimeout(()=>{
      this.treeData = [{"id":1,"title":"前端","children":[{"id":11,"title":"html"},{"id":12,"title":"css"},{"id":13,"title":"javascript"}]},{"id":2,"title":"后端","children":[{"id":21,"title":"php"},{"id":22,"title":"java"}]}];
    },5000);
  },
};
</script>

此时,树节点就没有正常展开。

继续测试,在节点初始化的时候,给树节点一部分数据:

<template>
  <a-tree
    :expandedKeys="expandedKeys"
    :tree-data="treeData"
    :replace-fields="{
      children: 'children',
      title: 'title',
      key: 'id',
    }"
  />
</template>

<script>
export default {
  data() {
    return {
      treeData: [{"id":1,"title":"前端","children":[{"id":11,"title":"html"},{"id":12,"title":"css"},{"id":13,"title":"javascript"}]}],
      expandedKeys: [1, 2],
    };
  },
  created(){
    setTimeout(()=>{
      this.treeData = [{"id":1,"title":"前端","children":[{"id":11,"title":"html"},{"id":12,"title":"css"},{"id":13,"title":"javascript"}]},{"id":2,"title":"后端","children":[{"id":21,"title":"php"},{"id":22,"title":"java"}]}];
    },5000);
  },
};
</script>

结果如图:

 

然后

大概和预想中一样,tree初始化成功,节点正常展开,后来数据再加载进来,也不会再次展开。

那么怎么让异步加载的数据也展开呢?

那么就判断数据加载成功了再初始化tree,就给tree加一个v-if判断就好了!

<template>
  <a-tree
    v-if="treeData.length > 0"
    :expandedKeys="expandedKeys"
    :tree-data="treeData"
    :replace-fields="{
      children: 'children',
      title: 'title',
      key: 'id',
    }"
  />
</template>

<script>
export default {
  data() {
    return {
      treeData: [],
      expandedKeys: [1, 2],
    };
  },
  created(){
    setTimeout(()=>{
      this.treeData = [{"id":1,"title":"前端","children":[{"id":11,"title":"html"},{"id":12,"title":"css"},{"id":13,"title":"javascript"}]},{"id":2,"title":"后端","children":[{"id":21,"title":"php"},{"id":22,"title":"java"}]}];
    },5000);
  },
};
</script>

问题就这样解决啦,如果你有更好的解决办法,欢迎留言谈论哦!

Logo

前往低代码交流专区

更多推荐