在Vue3+ElementPlus项目中使用具有懒加载的el-tree树形控件

简介: 在Vue 3和Element Plus项目中实现具有懒加载功能的el-tree树形控件,以优化大数据量时的页面性能。

前言

有时遇到一些需求就是在使用树形控件时,服务端并没有一次性返回所有数据,而是返回首层节点列表。然后点击展开首层节点中的某个节点,再去请求该节点的子节点列表,那么就得用上懒加载的机制了。在此以ElementPlus的树形控件为例,实现一个具有懒加载的树形控件的示例页面。

传送门:https://element-plus.gitee.io/zh-CN/component/tree.html

一、示例代码

(1)/src/views/Example/ElTreeLazy/index.vue

<template>
  <el-scrollbar v-loading="treeLoading" element-loading-text="数据正在渲染中..." class="element-plus-tree">
    <el-tree
      lazy
      ref="treeRef"
      :props="defaultProps"
      :data="treeData"
      :load="loadNode"
      :show-checkbox="false"
      :default-expand-all="false"
      :highlight-current="true"
      :expand-on-click-node="false"
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <span v-if="!data.leaf" class="node-folder">
          <el-icon v-if="node.expanded" style="margin: 0 6px 0 0px;" size="16"><FolderOpened /></el-icon>
          <el-icon v-else style="margin: 0 6px 0 0px;" size="16"><Folder /></el-icon>
          <small :title="node.label">{
  
  { node.label }}</small>
        </span>

        <span v-else class="node-file">
          <el-icon style="margin: 0 6px 0 0px;" size="16"><Document /></el-icon>
          <small :title="node.label">{
  
  { node.label }}</small>
        </span>
      </template>
    </el-tree>
  </el-scrollbar>
</template>

<script setup>
import {
    
     onMounted, onUnmounted, ref, getCurrentInstance, defineExpose } from 'vue'

// 代理对象
const {
    
     proxy } = getCurrentInstance()

// 树组件实例
const treeRef = ref(null)

// 树组件数据
const treeData = ref([])

// 加载中
const treeLoading = ref(true)

// 树节点属性映射关系
const defaultProps = {
    
    
  children: 'children',
  label: 'name',
  isLeaf: 'leaf',
}

/**
 * 加载节点
 */
const loadNode = async (node, resolve) => {
    
    
  // 首层节点,即:根节点
  if (node.level === 0) {
    
    
    resolve(node.data)
  }

  // 第二层节点
  if (node.level === 1) {
    
    
    // 判断某个节点的子节点列表是否非空,非空则不调用接口,否则调用接口查询该节点的列表
    if (node.data.children) {
    
    
      resolve(node.data.children)
    } else {
    
    
      setTimeout(() => {
    
    
        const res = {
    
     success: true, data: [] }
        if (res.success) {
    
    
          const nodeNum = parseInt(Math.random() * 10) + 1 // 1 ~ 10
          for (let i = 1; i <= nodeNum; i++) {
    
    
            res.data.push(
              {
    
    
                name: `哈哈哈-${
      
      i}`,
              }
            )
          }

          const hasChild = Math.random() > 0.5
          if (hasChild) {
    
    
            const childNum = parseInt(Math.random() * 5) + 1 // 1 ~ 5
            for (let vo of res.data) {
    
    
              vo.children = []
              for (let i = 1; i <= childNum; i++) {
    
    
                vo.children.push(
                  {
    
    
                    name: `嘻嘻嘻-${
      
      i}`,
                  }
                )
              }
            }
          }

          console.log('叶子节点加工前 =>', res)
          handleJudgeLeafrecursion(res.data)
          console.log('叶子节点加工后 =>', res)
        } else {
    
    
          proxy.$message({
    
     message: '请求失败', type: 'error', duration: 3000 })
        }
        node.data.children = res.data
        resolve(node.data.children)
      }, 200)
    }
  }

  // 第三层节点,以及其它层节点
  if (node.level > 1) {
    
    
    if (node.data.children && node.data.children.length > 0) {
    
    
      resolve(node.data.children)
    } else {
    
    
      resolve([])
    }
  }
}

/**
 * 获取首层节点数据列表
 */
const getFirstLevelNodeData = () => {
    
    
  const res = {
    
    
    success: true,
    data: ['香烟Wifi啤酒', '火腿iPad泡面', '骑着蜗牛散步', '都随它大小便吧', '没有强度,全是手法']
  }
  const list = []
  setTimeout(() => {
    
    
    if (res.success) {
    
    
      for (let i = 0; i < res.data.length; i++) {
    
    
        list.push(
          {
    
    
            'id': i + 1,
            'name': res.data[i],
          }
        )
      }
    } else {
    
    
      proxy.$message({
    
     message: '请求失败', type: 'error', duration: 3000 })
    }

    treeData.value = list
    treeLoading.value = false
  }, 200)
}

/**
 * 判断叶子节点递归方法
 */
const handleJudgeLeafrecursion = (list) => {
    
    
  for (let vo of list) {
    
    
    // 若无 children 或 children 大小为零,即判定该节点为叶子节点
    if (vo.children == null || vo.children.length == 0) {
    
    
      vo.leaf = true
    } else {
    
    
      handleJudgeLeafrecursion(vo.children)
    }
  }
}

/**
 * 树节点点击事件句柄方法
 */
const handleNodeClick = (data) => {
    
    
  console.log('handleNodeClick =>', data)
}

// 子组件通过 defineExpose 暴露指定的属性给父组件
defineExpose({
    
    
  treeRef, // 暴露树组件实例
})

onMounted(() => {
    
    
  getFirstLevelNodeData()
})

onUnmounted(() => {
    
    
  // ...
})
</script>

<style lang="less" scoped>
  .element-plus-tree {
    
    
    height: 100%;

    :deep(.el-tree) {
    
    
      padding-left: 5px;

      /* ---- ---- ---- ---- ^(节点对齐)---- ---- ---- ---- */
      .el-tree-node {
    
    

        /* ^ 所有节点 */
        i.el-tree-node__expand-icon {
    
    
          padding: 6px;
          margin-right: 5px;

          &::before {
    
    
            font-family: element-ui-icons;
            font-style: normal;
            content: "\e6d9";
            color: #000000;
            border: 1px solid #606266;
            border-radius: 2px;
          }

          svg {
    
    
            display: none; // 隐藏所有节点的 svg 图标
          }
        }
        /* / 所有节点 */

        /* ^ 已展开的父节点 */
        i.el-tree-node__expand-icon.expanded {
    
    
          transform: rotate(0deg); // 取消旋转
          -webkit-transform: rotate(0deg); // 取消旋转

          &::before {
    
    
            font-family: element-ui-icons;
            font-style: normal;
            content: "\e6d8";
            color: #000000;
            border: 1px solid #606266;
            border-radius: 2px;
          }
        }
        /* / 已展开的父节点 */

        /* ^ 叶子节点 */
        i.el-tree-node__expand-icon.is-leaf {
    
    

          &::before {
    
    
            display: none;
          }
        }
        /* / 叶子节点 */

        /* ^ 复选框 */
        .el-checkbox {
    
    
          margin: 0 7px 0 2px;

          .el-checkbox__inner {
    
    
            width: 14px;
            height: 14px;
            border-radius: 2px;
            border: 1px solid #bbb;
          }

          .el-checkbox__input.is-checked .el-checkbox__inner,
          .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    
    
            border: 1px solid #5e7ce0;
          }
        }
        /* / 复选框 */

        .el-tree-node__content {
    
    
          small {
    
    
            font-size: 13px;
            padding-right: 5px;
            transition: all ease 0.1s;
          }
        }
      }
      /* ---- ---- ---- ---- /(节点对齐)---- ---- ---- ---- */

      /* ---- ---- ---- ---- ^(文字/背景高亮)---- ---- ---- ---- */
      .el-tree-node {
    
    
        .el-tree-node__content {
    
    
          background-color: transparent;

          .node-root {
    
    
            display: flex;
            align-items: center;

            small {
    
    
              font-weight: bold;
              color: #40485c;
              transition: all ease 0.3s;
            }
          }

          .node-folders {
    
    
            display: flex;
            align-items: center;

            small {
    
    
              font-weight: bold;
              color: #40485c;
              transition: all ease 0.3s;
            }
          }

          .node-folder {
    
    
            display: flex;
            align-items: center;

            small {
    
    
              font-weight: bold;
              color: #40485c;
              transition: all ease 0.3s;
            }
          }

          .node-file {
    
    
            display: flex;
            align-items: center;

            small {
    
    
              font-weight: normal;
              color: #40485c;
              transition: all ease 0.3s;
            }
          }

          &:hover small {
    
    
              color: #5e7ce0;
          }
        }
      }

      .el-tree-node.is-current {
    
    
        .el-tree-node__content {
    
    

          small {
    
    
            color: #5e7ce0;
          }
        }

        .el-tree-node__children {
    
    
          small {
    
    
            color: unset;
          }
        }
      }

      &.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    
    
        background-color: #eff2fc;
        // background-color: #b6c7ff;

        i::before, i::after {
    
    
          // border-color: #fff;
          // color: #fff;
          border-color: #002293;
          color: #002293;
        }

        small {
    
    
          // color: #fff;
          color: #002293;
        }
      }
      /* ---- ---- ---- ---- /(文字/背景高亮)---- ---- ---- ---- */

      /* ---- ---- ---- ---- ^(新增辅助线)---- ---- ---- ---- */
      /* ^ 树节点 */
      .el-tree-node {
    
    
        position: relative;
        width: auto;
        width: max-content; // 显示文字宽度
        padding-left: 13px;

        &::before {
    
    
          width: 1px;
          height: 100%;
          content: '';
          position: absolute;
          top: -38px;
          bottom: 0;
          left: 0;
          right: auto;
          border-width: 1px;
          border-left: 1px solid #b8b9bb;
        }

        &::after {
    
    
          width: 13px;
          height: 13px;
          content: '';
          position: absolute;
          z-index: 0;
          left: 0;
          right: auto;
          top: 12px;
          bottom: auto;
          border-width: 1px;
          border-top: 1px solid #b8b9bb;
        }

        .el-tree-node__content {
    
    
          position: relative;
          z-index: 1;
          padding-left: 0 !important;

          /* ^ 复选框 */
          .el-checkbox {
    
    
            margin: 0 10px 0 0.5px;
          }
          /* / 复选框 */
        }

        .el-tree-node__children {
    
    
          padding-left: 12px;
        }

        &:last-child::before {
    
    
          height: 50px;
        }
      }
      /* / 树节点 */

      /* ^ 第一层节点 */
      > .el-tree-node {
    
    
        padding-left: 0;

        &::before {
    
    
          border-left: none;
        }

        &::after {
    
    
          border-top: none;
        }

        .el-tree-node__content {
    
    
          i.el-tree-node__expand-icon.is-leaf {
    
    
            margin-right: 5px;
          }
        }
      }
      /* / 第一层节点 */

      /* ---- ---- ---- ---- /(新增辅助线)---- ---- ---- ---- */
    }
  }
</style>

二、运行效果

目录
相关文章
|
23天前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
192 11
|
5月前
|
缓存 JavaScript PHP
斩获开发者口碑!SnowAdmin:基于 Vue3 的高颜值后台管理系统,3 步极速上手!
SnowAdmin 是一款基于 Vue3/TypeScript/Arco Design 的开源后台管理框架,以“清新优雅、开箱即用”为核心设计理念。提供角色权限精细化管理、多主题与暗黑模式切换、动态路由与页面缓存等功能,支持代码规范自动化校验及丰富组件库。通过模块化设计与前沿技术栈(Vite5/Pinia),显著提升开发效率,适合团队协作与长期维护。项目地址:[GitHub](https://github.com/WANG-Fan0912/SnowAdmin)。
787 5
|
7天前
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
71 0
|
2月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
311 1
|
2月前
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
161 0
|
3月前
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
104 0
|
5月前
|
JavaScript API 容器
Vue 3 中的 nextTick 使用详解与实战案例
Vue 3 中的 nextTick 使用详解与实战案例 在 Vue 3 的日常开发中,我们经常需要在数据变化后等待 DOM 更新完成再执行某些操作。此时,nextTick 就成了一个不可或缺的工具。本文将介绍 nextTick 的基本用法,并通过三个实战案例,展示它在表单验证、弹窗动画、自动聚焦等场景中的实际应用。
440 17
|
6月前
|
JavaScript 前端开发 算法
Vue 3 和 Vue 2 的区别及优点
Vue 3 和 Vue 2 的区别及优点
|
4月前
|
JavaScript 前端开发 UED
Vue 项目中如何自定义实用的进度条组件
本文介绍了如何使用Vue.js创建一个灵活多样的自定义进度条组件。该组件可接受进度段数据数组作为输入,动态渲染进度段,支持动画效果和内容展示。当进度超出总长时,超出部分将以红色填充。文章详细描述了组件的设计目标、实现步骤(包括props定义、宽度计算、模板渲染、动画处理及超出部分的显示),并提供了使用示例。通过此组件,开发者可根据项目需求灵活展示进度情况,优化用户体验。资源地址:[https://pan.quark.cn/s/35324205c62b](https://pan.quark.cn/s/35324205c62b)。
147 0
|
5月前
|
JavaScript 前端开发 API
Vue 2 与 Vue 3 的区别:深度对比与迁移指南
Vue.js 是一个用于构建用户界面的渐进式 JavaScript 框架,在过去的几年里,Vue 2 一直是前端开发中的重要工具。而 Vue 3 作为其升级版本,带来了许多显著的改进和新特性。在本文中,我们将深入比较 Vue 2 和 Vue 3 的主要区别,帮助开发者更好地理解这两个版本之间的变化,并提供迁移建议。 1. Vue 3 的新特性概述 Vue 3 引入了许多新特性,使得开发体验更加流畅、灵活。以下是 Vue 3 的一些关键改进: 1.1 Composition API Composition API 是 Vue 3 的核心新特性之一。它改变了 Vue 组件的代码结构,使得逻辑组
1529 0