TreeViewNode.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <template>
  2. <a-tree
  3. :tree-data="treeData" :checkable="isShowCheck" :expanded-keys="expandedKeys"
  4. :checked-keys="checkedKeys" :selected-keys="selectedKeys"
  5. :field-names="{ children: 'childrenDatas', key: 'id', title: 'text' }" @expand="handleExpand"
  6. @check="handleCheck"
  7. />
  8. <!-- @select="handleSelect" -->
  9. </template>
  10. <script>
  11. export default {
  12. name: 'TreeViewNode',
  13. props: {
  14. node: {
  15. type: Object,
  16. default: () => ({}),
  17. },
  18. isShowCheck: {
  19. type: Boolean,
  20. default: false,
  21. },
  22. isRoot: {
  23. type: Boolean,
  24. default: false,
  25. },
  26. },
  27. emits: ['nodeExpand', 'nodeSelect'],
  28. data() {
  29. return {
  30. expandedKeys: [],
  31. checkedKeys: [],
  32. selectedKeys: [],
  33. };
  34. },
  35. computed: {
  36. treeData() {
  37. return this.isRoot ? [this.node] : this.node.childrenDatas || [];
  38. },
  39. },
  40. watch: {
  41. node: {
  42. handler(newVal) {
  43. if (newVal.selected) {
  44. this.checkedKeys = [newVal.id];
  45. } else {
  46. this.checkedKeys = this.collectSelectedIds(newVal.childrenDatas || []);
  47. }
  48. },
  49. deep: true,
  50. immediate: true,
  51. },
  52. },
  53. methods: {
  54. handleExpand(expandedKeys) {
  55. this.expandedKeys = expandedKeys;
  56. const node = this.findNode(expandedKeys[expandedKeys.length - 1]);
  57. this.$emit('nodeExpand', node);
  58. },
  59. handleCheck(checkedKeys, { node }) {
  60. // this.checkedKeys = checkedKeys;
  61. this.$emit('nodeSelect', node.dataRef);
  62. },
  63. handleSelect(selectedKeys, { node }) {
  64. // this.selectedKeys = selectedKeys;
  65. this.$emit('nodeSelect', node.dataRef);
  66. },
  67. findNode(key) {
  68. const find = nodes => {
  69. for (const node of nodes) {
  70. if (node.id === key) return node;
  71. if (node.childrenDatas) {
  72. const found = find(node.childrenDatas);
  73. if (found) return found;
  74. }
  75. }
  76. };
  77. return find(this.treeData);
  78. },
  79. // 获取所有子节点中selected为true的ID
  80. collectSelectedIds(nodes, result = []) {
  81. const _self = this;
  82. if (!nodes || nodes.length === 0) return result;
  83. nodes.forEach(node => {
  84. if (node.selected) {
  85. result.push(node.id);
  86. } else {
  87. if (node.childrenDatas && node.childrenDatas.length > 0) {
  88. _self.collectSelectedIds(node.childrenDatas, result);
  89. }
  90. }
  91. });
  92. return result;
  93. },
  94. },
  95. };
  96. </script>