用原生TypeScript造轮子(六) Tree

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

简介

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

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

基本思路

用户需要传入一个相对固定的数据结构,比如:

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:

所以最重要的就是写出递归函数,demo中是这段:

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

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

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

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

export type DataTree = {
  title: string;
  expand?: boolean;
  selected?: boolean;
  nodeKey?: number;
  children?: DataTree[];
}

你可能感兴趣的:(typescript)