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>
相关推荐
胖者是谁3 分钟前
EasyPlayerPro的使用方法
前端·javascript·css
EndingCoder10 分钟前
索引类型和 keyof 操作符
linux·运维·前端·javascript·ubuntu·typescript
liux352818 分钟前
Web集群管理实战指南:从架构到运维
运维·前端·架构
沛沛老爹25 分钟前
Web转AI架构篇 Agent Skills vs MCP:工具箱与标准接口的本质区别
java·开发语言·前端·人工智能·架构·企业开发
摘星编程1 小时前
React Native for OpenHarmony 实战:ImageBackground 背景图片详解
javascript·react native·react.js
小光学长1 小时前
基于Web的长江游轮公共服务系统j225o57w(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库
摘星编程2 小时前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe5562 小时前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-20222 小时前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
摘星编程2 小时前
React Native for OpenHarmony 实战:GestureResponderSystem 手势系统详解
javascript·react native·react.js