巧用Vue3 composition api的计算属性实现扁平化tree连线

本示例节选自vue3最新开源组件实战教程大纲(持续更新中)的tree组件开发部分。将进一步把基于Vue3 composition api的computed计算属性特性应用到组件开发实战中,继续以最佳实践的方式呈现给大家。

下面我们要实现的是扁平化的dom结构所呈现的树形组件增加参照线的功能。

这种结构不同于传统嵌套dom实现的树作参照线那么简单,需要动态计算线的长度,正好我们可以充分应用vue3给我们提供的composition api的计算属性computed。一切都变得非常简单,Life is so easy!

节点属性

新增节点属性

ts 复制代码
export interface ITreeNode {
  ...
  visibleLength?: ComputedRef<number> // 展开可见的节点长度
  lineLength?: ComputedRef<number> // 节点参照线的长度
}

计算属性

核心的初始化方法

ts 复制代码
function initParentNode(node: ITreeNode, optionProps: OptionProps) {
  const nodeRef = ref<ITreeNode>(node)
  const childrenName = optionProps.childrenName as 'children'
  // 可见节点长度计算属性
  node.visibleLength = computed(() => {
    // 如果不是展开的返回0
    if (!nodeRef.value.expanded) return 0
    // 遍历原始树结构的子节点列表,判断如果是父节点,则继续递归调用其visibleLength计算属性
    // 通过reduce实现累加
    return nodeRef.value[childrenName]!.reduce((count, cur) => count + (cur[childrenName] ? (cur.expanded ? 1 + cur.visibleLength! : 1) : 1), 0)
  })
  // 计算父节点的参照线长度
  node.lineLength = computed(() => {
    // 如果是折叠的直接返回0
    if (!nodeRef.value.expanded) return 0
    // 否则用可见长度 - 子一代最后一个节点的可见长度
    const children = nodeRef.value[childrenName]
    const lastChild = children![children!.length - 1]
    return nodeRef.value.visibleLength! - (lastChild.visibleLength || 0)
  })
}

在拍平函数中调用父节点初始化函数:

组件完善

模板完善

试着打印父节点的参照线长度

看下效果:

展开、折叠,参照线并不会动态变化。修复下:

再看效果,删除节点测试还有问题:

修复下:

完美!

相关推荐
FungLeo2 天前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome
FungLeo2 天前
成为全栈·Vue管理后台篇·<scriptsetup>:把页面拆成可读、可测的 Vue 组件
前端·javascript·vue.js·typescript·前端组件化·composition api·vue sfc
周大侠0053 天前
从 Webpack 到 Vite:30 个存量项目的迁移踩坑与灰度方案
webpack·vite
晓得迷路了4 天前
栗子前端技术周刊第 153 期 - Vitest 5.1、Remix v3.2、Node.js 27 Alpha...
前端·javascript·vite
theMuseCatcher5 天前
Vue3导航菜单(Menu)
typescript·vue3·less
theMuseCatcher6 天前
Vue3评论(Comment)
typescript·vue3
RuoyiOffice7 天前
Vue3+Gantt:把任务排期、依赖关系和里程碑放进项目管理
项目管理·vue3·springboot·dhtmlx-gantt·wbs·gantt·ruoyi office
AI开源软件9 天前
SpringBoot3+Vue3 财务管理系统如何设计:从业务单据到总账的模块划分
spring boot·vue3·领域建模·会计凭证·ruoyi office·业财协同·财务系统设计
Nymph_Zhu13 天前
vue3+element-plus 文件上传
前端·typescript·vue3·element-plus
Nymph_Zhu13 天前
pdf转换markdown预览及内容互相点击定位
前端·pdf·vue3·markdown·element-plus