遇到个需求,每次打开页面时tree组件需要默认展开到第几层,记录一下。

先看看基础用法,展示可勾选,可选中,禁用,默认展开等功能。

更多用法可以去看 树形控件 Tree - Ant Design Vue (antdv.com)

<template>
  <a-tree
    checkable
    :tree-data="treeData"
    :default-expanded-keys="['0-0-0', '0-0-1']"
    :default-selected-keys="['0-0-0', '0-0-1']"
    :default-checked-keys="['0-0-0', '0-0-1']"
    @select="onSelect"
    @check="onCheck"
  >
    <span slot="title0010" style="color: #1890ff">sss</span>
  </a-tree>
</template>
<script>
const treeData = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          { title: 'leaf', key: '0-0-0-0', disableCheckbox: true },
          { title: 'leaf', key: '0-0-0-1' },
        ],
      },
      {
        title: 'parent 1-1',
        key: '0-0-1',
        children: [{ key: '0-0-1-0', slots: { title: 'title0010' } }],
      },
    ],
  },
];

export default {
  data() {
    return {
      treeData,
    };
  },
  methods: {
    onSelect(selectedKeys, info) {
      console.log('selected', selectedKeys, info);
    },
    onCheck(checkedKeys, info) {
      console.log('onCheck', checkedKeys, info);
    },
  },
};
</script>

:default-expanded-keys表示的是默认展开的值,我的思路是:default-expanded-keys="expandedKeys",然后在获取数据时对这个expandedKeys进行添加操作,如下:

<script>
    export default{
        name:'demo',
        data(){
            return{
                demoList:[]
            }
        },
        methods:{
            getExpendKeys(){
            //demoList是树的option项
                this.demoList.forEach(v => {
                    if (v.children) {
                      this.expandedKeys.push(v.id);
                        //若继续往下展开则添加下面的语句,以此类推
                        //v.children.forEach(el => {
                        //this.expandedKeys.push(el.id);
                      //})
                }
              })
            }
        }
    }
</script>

Logo

前往低代码交流专区

更多推荐