use-tree.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import { computed, ref } from 'vue'
  2. export const useTree = (props, { emit }) => {
  3. const config = computed(() => {
  4. return props.config ?? {}
  5. })
  6. // 头部按钮
  7. const appendTree = () => {
  8. emit('node-append', {})
  9. }
  10. const reload = () => {
  11. emit('tree-reload')
  12. }
  13. const defaultProps = computed(() => {
  14. return Object.assign({}, {
  15. children: 'children',
  16. label: 'label'
  17. }, config.value.defaultProps, config.value.optionProps)
  18. })
  19. const isTreeAppend = computed(() => {
  20. return config.value.isTreeAppend ?? false
  21. })
  22. // 节点唯一标识
  23. const nodeKey = computed(() => {
  24. return config.value.nodeKey ?? 'id'
  25. })
  26. // 是否手风琴模式
  27. const accordion = computed(() => {
  28. return config.value.accordion ?? false
  29. })
  30. // 懒加载函数
  31. const lazyLoad = computed(() => {
  32. return config.value.lazyLoad ?? null
  33. })
  34. // 是否进入展开,使用懒加载时默认不展开,不使用时默认展开
  35. const expandOnClickNode = computed(() => {
  36. return config.value.expandOnClickNode
  37. })
  38. // 且不是手风琴模式才可以默认展开
  39. const defaultExpandAll = computed(() => {
  40. return config.value.defaultExpandAll ?? !lazyLoad.value
  41. })
  42. // 显示checkbox
  43. const showCheckbox = computed(() => {
  44. return config.value.showCheckbox ?? false
  45. })
  46. // 树形组件搜索
  47. const filterNode = (value, data) => {
  48. if (!value) return true
  49. return data[defaultProps.value.label].indexOf(value) !== -1
  50. }
  51. // 定义渲染层级
  52. const level = computed(() => {
  53. return config.value.treeLevel ?? 0
  54. })
  55. // 定义树按钮渲染层级
  56. const buttonLevel = computed(() => {
  57. return config.value.buttonLevel
  58. })
  59. // 显示按钮类型列表
  60. const buttonList = computed(() => {
  61. return config.value.buttonList ?? []
  62. })
  63. // 点击树节点
  64. const nodeClick = (data, node, comp) => {
  65. // 清除高亮后手动开启,配置中不开启高亮则跳过
  66. if (config.value.highlightCurrent && !highlightCurrent.value) {
  67. highlightCurrent.value = true
  68. }
  69. console.log(data, node, comp)
  70. emit('node-click', { data, node, comp })
  71. }
  72. // 是否高亮当前节点
  73. const highlightCurrent = ref(false)
  74. highlightCurrent.value = !!config.value.highlightCurrent
  75. // 一些重置操作需要清除高亮,只能手动清除
  76. const clearHighlight = () => {
  77. highlightCurrent.value = false
  78. }
  79. return {
  80. config,
  81. appendTree,
  82. reload,
  83. defaultProps,
  84. isTreeAppend,
  85. nodeKey,
  86. accordion,
  87. lazyLoad,
  88. expandOnClickNode,
  89. defaultExpandAll,
  90. showCheckbox,
  91. filterNode,
  92. level,
  93. buttonLevel,
  94. buttonList,
  95. nodeClick,
  96. highlightCurrent,
  97. clearHighlight
  98. }
  99. }