官网链接: https://1x.antdv.com/components/tree-select-cn/
// An highlighted block
最近做了一个二次开发的ant-design-vue项目,这里记录下我写项目遇到的一些问题
项目有一个需求,需要treeSelect树节点回显,当时看了一下代码,人都傻了,十分杂乱,
用的组件传值方式是this.$refs,当时看代码一群的这个数据,个人更倾向是传统的props和emit
这里谈下问题
1.怎么编辑回显treeSelect呢,当时这个疑问了我好几天,去官网和github搜了半天issue才发现了几个回答,官网也是没有很详细的写出怎么异步加载子节点,他
只示例了几个一级数据回显和手动点击二级树回显列表
官网示例
<template>
<a-tree-select
v-model="value"
tree-data-simple-mode
style="width: 100%"
:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
:tree-data="treeData"
placeholder="Please select"
:load-data="onLoadData"
/>
</template>
<script>
export default {
data() {
return {
value: undefined,
treeData: [
{ id: 1, pId: 0, value: '1', title: 'Expand to load' },
{ id: 2, pId: 0, value: '2', title: 'Expand to load' },
{ id: 3, pId: 0, value: '3', title: 'Tree Node', isLeaf: true },
],
};
},
watch: {
value(value) {
console.log(value);
},
},
methods: {
genTreeNode(parentId, isLeaf = false) {
const random = Math.random()
.toString(36)
.substring(2, 6);
return {
id: random,
pId: parentId,
value: random,
title: isLeaf ? 'Tree Node' : 'Expand to load',
isLeaf,
};
},
onLoadData(treeNode) {
return new Promise(resolve => {
const { id } = treeNode.dataRef;
setTimeout(() => {
this.treeData = this.treeData.concat([
this.genTreeNode(id, false),
this.genTreeNode(id, true),
]);
resolve();
}, 300);
});
},
},
};
</script>
这里主要记录下各个属性的意思
treeData:一级数据
loadData:加载二级或者多级节点的方法
v-model: 代表当前值选中
tree-data-simple-mode:注意这个属性,将labelInValue强制转化为true,!!!注意这里是个坑
labelInValue:是否把每个选项的 label 包装到 value 中,
会把 value 类型从 string 变为 {value: string, label: VNode
, halfChecked(treeCheckStrictly 时有效): string[] } 的格式
这里贴下我写的代码,注意我这里写了treeCheckStrickly和labelInValue,一开始
我是没想到这个,觉得回显的东西不在这上面,没想到…,废话说了这么多,回显数据
主要靠labelInValue这个属性,他将v-model绑定的字符串变为了对象,属性是value和label:就是
id和name,当你只写treeCheckStrickly而不用labelInValue时没有用,当时没注意为什么,现在
也没空去看了,当你写了这个labelInValue时,你就可以拿到后端返回的二级数据通过v-model和labelInvalue去显示它