You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.5 KiB

1 year ago
  1. // pages/common/comTree/index.js
  2. /**
  3. value = [
  4. {
  5. id: 1,
  6. name: '一级名称',
  7. children: []
  8. }
  9. ]
  10. */
  11. Component({
  12. /**
  13. * 组件的属性列表
  14. */
  15. properties: {
  16. dataTree: {
  17. type: Array,
  18. value: []
  19. },
  20. selectKey: { // 选中的节点id
  21. type: String,
  22. value: ''
  23. },
  24. isSelectLastNode: { //是否必须选中最后一节点
  25. type: Boolean,
  26. value: false
  27. },
  28. isOpenAll: { //是否展开全部节点
  29. type: Boolean,
  30. value: false
  31. }
  32. },
  33. observers: {
  34. 'dataTree': function(params) {
  35. let dataTree = JSON.parse(JSON.stringify(this.properties.dataTree))
  36. var tree = this.findParent(dataTree,this.properties.selectKey,[])
  37. params.forEach(v => {
  38. if(v.id == tree[0]){
  39. v.open = true
  40. }else{
  41. v.open = this.properties.isOpenAll // 是否展开
  42. }
  43. })
  44. this.setData({
  45. tree:params
  46. })
  47. }
  48. },
  49. /**
  50. * 组件的初始数据
  51. */
  52. data: {
  53. tree: []
  54. },
  55. /**
  56. * 组件的方法列表
  57. */
  58. methods: {
  59. findParent(data, target, result) {
  60. for (let i in data) {
  61. let item = data[i]
  62. if (item.id == target) {
  63. //将查找到的目标数据加入结果数组中
  64. //可根据需求unshift(item.id)或unshift(item)
  65. item.open = true
  66. result.unshift(item.id)
  67. return result
  68. }
  69. if (item.children && item.children.length > 0) {
  70. let ok = this.findParent(item.children, target, result)
  71. if (ok) {
  72. item.open = true
  73. result.unshift(item.id)
  74. return result
  75. }
  76. }
  77. }
  78. //走到这说明没找到目标
  79. return false
  80. },
  81. isOpen(e) {
  82. const open = 'tree[' + e.currentTarget.dataset.index + '].open'
  83. this.setData({
  84. [open]: !this.data.tree[e.currentTarget.dataset.index].open
  85. })
  86. },
  87. select(e) {
  88. const item = e.currentTarget.dataset.item
  89. if(this.properties.isSelectLastNode) {
  90. // console.log(item)
  91. this.triggerEvent('select', { item: item }, { bubbles: true, composed: true })
  92. // if (!item.children || item.children.length == 0) {
  93. // this.triggerEvent('select', { item: item }, { bubbles: true, composed: true })
  94. // } else {
  95. // this.triggerEvent('select', { tips: '必须选择最后一个节点' }, { bubbles: true, composed: true })
  96. // }
  97. } else {
  98. this.triggerEvent('select', { item: item }, { bubbles: true, composed: true })
  99. }
  100. }
  101. }
  102. })