index.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <template>
  2. <avue-cascader placeholder="请选择" check-strictly v-model="cascaderVal" :dic="list"></avue-cascader>
  3. </template>
  4. <script>
  5. import { getList } from "@/api/basicResource/compDeptList";
  6. export default {
  7. name: 'wwProjectCascader',
  8. props: {
  9. value: [Array],
  10. // 搜索条件
  11. yearAndMonth: [String, Number],
  12. disabled: {
  13. type: Boolean,
  14. default: false
  15. },
  16. },
  17. data() {
  18. return {
  19. cascaderVal: [],
  20. list: []
  21. }
  22. },
  23. watch: {
  24. cascaderVal(newVal) {
  25. this.$emit('input', newVal);
  26. },
  27. yearAndMonth(newVal) {
  28. this.getListFunc();
  29. },
  30. },
  31. methods: {
  32. buildTree(flatList, options = {}) {
  33. const {
  34. idKey = "id", // 节点ID的键名
  35. parentKey = "parentId", // 父节点ID的键名
  36. childrenKey = "children", // 子节点列表的键名
  37. } = options;
  38. const nodeMap = {}; // 用于快速查找节点的映射表
  39. const tree = []; // 最终生成的树
  40. // 第一次遍历:创建所有节点的映射
  41. flatList.forEach((node) => {
  42. nodeMap[node[idKey]] = {
  43. ...node,
  44. label: node.name,
  45. value: node.id,
  46. [childrenKey]: [],
  47. };
  48. });
  49. // 第二次遍历:构建父子关系
  50. flatList.forEach((node) => {
  51. const parentId = node[parentKey];
  52. if (
  53. parentId !== null &&
  54. parentId !== undefined &&
  55. nodeMap[parentId]
  56. ) {
  57. // 如果有父节点,则将当前节点添加到父节点的children中
  58. nodeMap[parentId][childrenKey].push(nodeMap[node[idKey]]);
  59. } else {
  60. // 如果没有父节点或父节点不存在,则作为根节点
  61. tree.push(nodeMap[node[idKey]]);
  62. }
  63. });
  64. return tree;
  65. },
  66. loopData(data) {
  67. return data.map(item => {
  68. item.children = item.children.length ? item.children : undefined;
  69. this.loopData(item.children || []);
  70. return item;
  71. });
  72. },
  73. getListFunc() {
  74. if (!this.yearAndMonth) {
  75. return;
  76. }
  77. getList({ yearAndMonth: this.yearAndMonth }).then(({ data }) => {
  78. if (data.success) {
  79. let treeData = this.buildTree(data.data);
  80. this.list = this.loopData(treeData);
  81. this.cascaderVal = this.value || [];
  82. }
  83. })
  84. },
  85. }
  86. }
  87. </script>