用原生TypeScript造轮子(六) Tree

ui参考primeNG: http://primefaces.org/primeng...
ts开发环境: https://github.com/lycHub/ts-...
目录

简介

本节demo源码
参考ivew tree的内部实现,完成其部分功能
已实现的功能:node

  • 默认展开
  • 默认选中
  • 单/多选

基本思路

用户须要传入一个相对固定的数据结构,好比:git

const data = [
  {
    title: 'parent 1',
    expand: true,
    children: [
      {
        title: 'parent 1-1',
        expand: true,
        selected: true,
        children: [
          {
            title: 'leaf 1-1-1'
          },
          {
            title: 'leaf 1-1-2'
          }
        ]
      },
      {
        title: 'parent 1-2',
        children: [
          {
            title: 'leaf 1-2-1'
          },
          {
            title: 'leaf 1-2-1'
          }
        ]
      }
    ]
  },
  {
    title: 'parent 2',
    expand: true,
    children: [
      {
        title: 'parent 2-1',
        children: [
          {
            title: 'leaf 2-1-1'
          },
          {
            title: 'leaf 2-1-2',
            selected: true
          }
        ]
      },
      {
        title: 'parent 2-2',
        expand: true,
        children: [
          {
            title: 'leaf 2-2-1'
          },
          {
            title: 'leaf 2-2-2'
          }
        ]
      }
    ]
  }
];

而后根据这个data, 用递归函数渲染出dom,每一个children都对应一个ul:github

clipboard.png

因此最重要的就是写出递归函数,demo中是这段:segmentfault

clipboard.png

这里只是组装dom结构,还须要再写个递归函数,把dom和用户传入的data对应起来:数据结构

clipboard.png

这个函数给每item加了个nodeKey做为标识,在上面渲染dom,只要把这个nodeKey存在dom中,dom

clipboard.png

那么在点击选中时,就能映射到对应的item数据了:函数

clipboard.png

还有个点是,ts中对于地归类的数据类型,能够以下设置:ui

export type DataTree = {
  title: string;
  expand?: boolean;
  selected?: boolean;
  nodeKey?: number;
  children?: DataTree[];
}
相关文章
相关标签/搜索