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>
相关推荐
嘗_6 分钟前
暑期前端训练day5
前端
uncleTom66612 分钟前
前端布局利器:rem 适配全面解析
前端
谦哥15 分钟前
Claude4免费Vibe Coding!目前比较好的Cursor替代方案
前端·javascript·claude
LEAFF26 分钟前
如何 测试Labview是否返回数据 ?
前端
Spider_Man28 分钟前
🚀 从阻塞到丝滑:React中DeepSeek LLM流式输出的实现秘籍
前端·react.js·llm
心在飞扬30 分钟前
理解JS事件环(Event Loop)
前端·javascript
敲代码的玉米C33 分钟前
深入理解链表反转:从基础到进阶的完整指南
javascript
盏茶作酒291 小时前
打造自己的组件库(一)宏函数解析
前端·vue.js
山有木兮木有枝_1 小时前
JavaScript 设计模式--单例模式
前端·javascript·代码规范
一大树1 小时前
Vue3 开发必备:20 个实用技巧
前端·vue.js