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>
相关推荐
旷世奇才李先生1 天前
Vue3\+Vite\+Pinia实战:企业级后台管理系统完整实现(附源码)
vue.js
不会聊天真君6471 天前
JavaScript基础语法(Web前端开发笔记第三期)
前端·javascript·笔记
齐鲁大虾1 天前
新人编程语言选择指南
javascript·c++·python·c#
IT_陈寒1 天前
SpringBoot自动配置这破玩意儿又坑我一次
前端·人工智能·后端
妖精的羽翼1 天前
前端(Vue)→ 全栈 + AI 应用开发
前端
码路飞1 天前
玩了一圈 AI 编程工具,Background Agent 才是让我真正震撼的东西
前端·javascript
UCloud_TShare1 天前
优刻得发布云搜索服务CSS:面向AI时代的企业级搜索基础设施
前端·css·人工智能
林恒smileZAZ1 天前
Three.js实现更真实的3D地球[特殊字符]动态昼夜交替
开发语言·javascript·3d
月月大王的3D日记1 天前
别再复制粘贴了,从零拆解 3D 场景的诞生过程
javascript