| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- <template>
- <avue-cascader placeholder="请选择" check-strictly v-model="cascaderVal" :dic="list"></avue-cascader>
- </template>
- <script>
- import { getList } from "@/api/basicResource/compDeptList";
- export default {
- name: 'wwProjectCascader',
- props: {
- value: [Array],
- // 搜索条件
- yearAndMonth: [String, Number],
- disabled: {
- type: Boolean,
- default: false
- },
- },
- data() {
- return {
- cascaderVal: [],
- list: []
- }
- },
- watch: {
- cascaderVal(newVal) {
- this.$emit('input', newVal);
- },
- yearAndMonth(newVal) {
- this.getListFunc();
- },
- },
- methods: {
- buildTree(flatList, options = {}) {
- const {
- idKey = "id", // 节点ID的键名
- parentKey = "parentId", // 父节点ID的键名
- childrenKey = "children", // 子节点列表的键名
- } = options;
- const nodeMap = {}; // 用于快速查找节点的映射表
- const tree = []; // 最终生成的树
- // 第一次遍历:创建所有节点的映射
- flatList.forEach((node) => {
- nodeMap[node[idKey]] = {
- ...node,
- label: node.name,
- value: node.id,
- [childrenKey]: [],
- };
- });
- // 第二次遍历:构建父子关系
- flatList.forEach((node) => {
- const parentId = node[parentKey];
- if (
- parentId !== null &&
- parentId !== undefined &&
- nodeMap[parentId]
- ) {
- // 如果有父节点,则将当前节点添加到父节点的children中
- nodeMap[parentId][childrenKey].push(nodeMap[node[idKey]]);
- } else {
- // 如果没有父节点或父节点不存在,则作为根节点
- tree.push(nodeMap[node[idKey]]);
- }
- });
- return tree;
- },
- loopData(data) {
- return data.map(item => {
- item.children = item.children.length ? item.children : undefined;
- this.loopData(item.children || []);
- return item;
- });
- },
- getListFunc() {
- if (!this.yearAndMonth) {
- return;
- }
- getList({ yearAndMonth: this.yearAndMonth }).then(({ data }) => {
- if (data.success) {
- let treeData = this.buildTree(data.data);
- this.list = this.loopData(treeData);
- this.cascaderVal = this.value || [];
- }
- })
- },
- }
- }
- </script>
|