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>
相关推荐
风骏时光牛马36 分钟前
AI源码分析:拆解模型底层实现逻辑
前端
BillKu44 分钟前
全局样式变量:CSS 自定义属性(--border-color)和SCSS 变量($border-color)的说明
javascript·css·scss
IT_陈寒1 小时前
React子组件莫名其妙重渲染?你可能漏了这个Hook
前端·人工智能·后端
乘风gg1 小时前
DeepSeek V4.1 Flash 来了,明天中午 Flash 降价 60%
前端·ai编程·claude
默_笙1 小时前
❗ 给金鱼装记忆(上):从白板到笔记本,AI 的短期记忆生存指南
前端·javascript
酷酷的逗逗乐2 小时前
前端转 Agent 开发 · 第五节:Memory 会话记忆
前端·程序员
掘金挖土2 小时前
前端手摸手跑路之 AI 应用开发(二)
前端·后端
兜里只有三分钱~2 小时前
翻卡_3D 的仪式感,和三个让它穿帮的写法
javascript·css·3d
mayaairi2 小时前
Vue2 组件通讯(四):v-model、scoped样式、mixins与plugins
前端·javascript·vue.js
梦曦i3 小时前
@meng-xi/uni-router 未来展望:夯实基础、深化体验、探索前沿
前端·uni-app