vue3+ el-tree 展开和折叠,默认展开第一项

默认第一项展开:

展开所有项:

折叠所有项:

javascript 复制代码
<template>
  <el-tree
    style="max-width: 600px"
    :data="treeData"
    node-key="id"
    :default-expanded-keys="defaultExpandedKey"
    :props="defaultProps"
    ref="treeRef"
  />
  <el-button @click="expandAll" type="primary" plain>展开所有</el-button>
  <el-button @click="collapseAll" type="success" plain>折叠所有</el-button>
</template>

<script setup>
import { ref } from 'vue'
const defaultProps = {
  children: 'children',
  label: 'label',
}
const treeData = ref([])
const treeRef = ref(null)
const defaultExpandedKey= ref([])

const expandAll = () => {
  treeRef.value.store._getAllNodes().forEach(node => {
    node.expanded = true;
  });
}

const collapseAll = () => {
  treeRef.value.store._getAllNodes().forEach(node => {
    node.expanded = false;
  });
}
// 此处使用定时器渲染数据,实际情况发送请求获取数据之后再设置
setTimeout(()=>{
  defaultExpandedKey.value = ['1','4']
  treeData.value = data
},1000)

const getTreeData = async () => {
  const { data } = await getTreeList();
  treeData.value = data;
  defaultExpandedKey.value = data[0].map((item) => item.id);
};

const data = [
  {
    id: 1,
    label: 'Level one 1',
    children: [
      {
        id: 4,
        label: 'Level two 1-1',
        children: [
          {
            id: 9,
            label: 'Level three 1-1-1',
          },
          {
            id: 10,
            label: 'Level three 1-1-2',
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: 'Level one 2',
    children: [
      {
        id: 5,
        label: 'Level two 2-1',
      },
      {
        id: 6,
        label: 'Level two 2-2',
      },
    ],
  },
  {
    id: 3,
    label: 'Level one 3',
    children: [
      {
        id: 7,
        label: 'Level two 3-1',
      },
      {
        id: 8,
        label: 'Level two 3-2',
      },
    ],
  },
]
</script>
相关推荐
站在风口的猪110810 分钟前
《前端面试题:CSS预处理器(Sass、Less等)》
前端·css·html·less·css3·sass·html5
程序员的世界你不懂35 分钟前
(9)-Fiddler抓包-Fiddler如何设置捕获Https会话
前端·https·fiddler
MoFe140 分钟前
【.net core】天地图坐标转换为高德地图坐标(WGS84 坐标转 GCJ02 坐标)
java·前端·.netcore
去旅行、在路上1 小时前
chrome使用手机调试触屏web
前端·chrome
Aphasia3112 小时前
模式验证库——zod
前端·react.js
lexiangqicheng2 小时前
es6+和css3新增的特性有哪些
前端·es6·css3
拉不动的猪3 小时前
都25年啦,还有谁分不清双向绑定原理,响应式原理、v-model实现原理
前端·javascript·vue.js
烛阴3 小时前
Python枚举类Enum超详细入门与进阶全攻略
前端·python
孟孟~3 小时前
npm run dev 报错:Error: error:0308010C:digital envelope routines::unsupported
前端·npm·node.js
孟孟~3 小时前
npm install 报错:npm error: ...node_modules\deasync npm error command failed
前端·npm·node.js