巧用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)
  })
}

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

组件完善

模板完善

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

看下效果:

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

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

修复下:

完美!

相关推荐
Sapphire~1 天前
Vue3-15 html标签和组件上的ref属性 + 接口泛型
vue3
Irene19912 天前
Vue 3 中使用 Mitt 事件总线
vue3·mitt
咸甜适中2 天前
双色球、大乐透兑奖分析小程序(rust_Tauri + Vue3 + sqlite)
爬虫·rust·sqlite·vue3·tauri2
Sapphire~4 天前
Vue3-012 vue2与vue3中的computed
vue3
Sapphire~6 天前
Vue3-11 toRefs 和 toRef
vue3
zhengxianyi5156 天前
vite build 发布到nginx二级目录——将yudao-ui-go-view打包、部署到big目录下
vue.js·nginx·vite·前后端分离·打包·ruoyi-vue-pro优化·部署运维
Mast Sail7 天前
WebStrom+Vitesse+Vue3项目路径报错爆红问题
vue·vite·webstorm
华玥作者8 天前
uni-app + Vite 项目中使用 @uni-helper/vite-plugin-uni-pages 实现自动路由配置(超详细)
前端·uni-app·vue·vue3·vite
独立开发者阿乐9 天前
Vue3中Markdown解析与渲染的完整解决方案:从安全到性能优化
web安全·性能优化·vue3·前端开发·语法高亮·markdown解析·markdown-it
Sapphire~10 天前
Vue3-10 ref与reactive创建响应式数据的区别
vue3