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>
相关推荐
xy34536 分钟前
Axure9.0 中继器遮罩的核心应用场景(精准适配列表交互)
前端·ui·html·原型·产品设计·axure9.0
天道kabuto13 分钟前
记一次 UnoCSS 样式离奇失效的踩坑复盘
前端
前端小张同学17 分钟前
AI全栈开发最佳实践💐
前端·后端·架构
前端 贾公子25 分钟前
第09章:上下文与记忆 (6)
开发语言·前端·python
用户9314563556627 分钟前
接口幂等性设计:从原理到落地,一篇讲透
前端
柚yuzumi28 分钟前
别再猜 this:先看它属于谁,再看它指向谁
前端·javascript
YIAN31 分钟前
React + Zustand + JWT 前端权限体系完整实现:从登录鉴权到路由守卫全流程拆解
前端·react.js·架构
汉堡大王952735 分钟前
面试必考:手写代码 new 做了什么?从原理到实现全解析
前端·javascript·面试
BillKu1 小时前
TypeScript中,字符串字面量联合类型(Union Type)、enum的用法说明
前端·javascript·typescript
jayson.h1 小时前
PDF 合并+添加页码 相关库、类、函数
开发语言·前端·python