背景
某些情况下使用级联器时需要将已有的数据加载到级联器选择列表中,此时使用懒加载会使多级选项丢失,如图:
-
懒加载前 -
懒加载后
解决方法
- 初始化级联器选项(options)时,将已选列表加入选项。此方法仅限于已选列表数据均为最后一层的情况。否则也会触发懒加载造成数据丢失。
export const Mixins = {
data() {
return {};
},
methods: {
createCascadorOptionsFromArray(origin) {
let container = {};
origin.map(path => {
this.genPathTier(container, path.split('/'));
})
return Object.entries(container).map(
([key, val]) => this.createCascadorOptionsFromPathArray(key, val)
);
},
genPathTier(container, pathArray) {
if (pathArray.length > 1) {
let parent = pathArray.shift();
if (!container[parent]) {
container[parent] = {};
}
this.genPathTier(container[parent], pathArray);
} else {
container[pathArray.shift()] = [];
}
},
createCascadorOptionsFromPathArray(cur, childrenTier) {
if (Object.keys(childrenTier).length) {
return {
value: cur, label: cur,
children: Object.entries(childrenTier).map(
([key, val]) => this.createCascadorOptionsFromPathArray(key, val)
)
};
} else {
return {value: cur, label: cur}
}
}
},
}
import {Mixins} from "./Mixins";
mixins: [Mixins],
methods: {
genCascaderOptions(){
CusApi.getPathTree().then(res => {
this.PathCascaderOptions = this.createCascadorOptionsFromArray(
[...res.data.TreeResponse, ...this.formData.path || []]
);
})
}
}
- 懒加载前保存已选列表,懒加载后重新渲染。
gitbasePathCascaderProps: {
lazy: true,
lazyLoad: async (node, resolve) => {
const {path} = node;
let originSelectPath = [...this.formData.path];
if ((node.children || []).length) {
resolve();
} else {
await CusApi.getPathTree().then(res => {
if (res.status === 200) {
resolve(res.data.Response.map(path => {
return {value: path, label: path, children: []};
}));
} else {
resolve();
}
});
}
this.$nextTick(() => {
this.formData.path = [];
this.formData.path = originSelectPath;
});
},
},
|