element-ui 2的级联选择器,懒加载模式下,回显已存储的子选项名称
文章目录
- 初始化级联选择控件
- 回显已存储的子选项
https://element.eleme.io/#/en-US/component/cascader
初始化级联选择控件
options提供用于初始化的一级选项
<el-cascaderref="cascader1":options="firstLevelOptions"collapse-tags:props="lazyLoadSettings"v-model="checkedAry">
props里配置懒加载具体实现
data() {return {firstLevelOptions: [],lazyLoadSettings: {lazy: true,multiple: true,lazyLoad(node, resolve) {// 加载第二级的选项列表,children初始化过,则不需再重新获取数据if (node.level === 1 && !!node.children) {const query = node.data.value;queryNextLevelOptions(query).then(resp => {const options = resp.data.map(item => ({value: item.optionId,label: item.optionName,leaf: true}));resolve(options);});} else {resolve([]);}}}}
}
回显已存储的子选项
因为是懒加载,所以二级选项都不存在,默认无法回显已选择的子选项名称;
需要在控件的一级选项(options)里主动注入savedValues所涉及的二级选项列表
async getFirstLevelOptions() {const resp = await request.get("aaa/bbb/ccc");const options = resp.data.map(item => ({value: item.optionId;label: item.optionName;}));return options;
}async initCascaderValue(savedValues) {if (this.firstLevelOptions.length === 0) {this.firstLevelOptions = await this.getFirstLevelOptions();}savedValues.forEach(selectedValue => {this.firstLevelOptions.forEach(firstLevel => {// 单个selectedValue的格式是['level1Value', 'level2Value']if (firstLevel.value === selectedValue[0] && !firstLevel.children) {// 按需加载二级选项的列表,让children数组内的子项触发控件展示数据的更新this.$set(firstLevel, "children", []);queryNextLevelOptions(firstLevel.value).then(resp => {resp.data && resp.data.forEach(item => {const option = {}option.value = item.optionId;option.label = item.optionName;option.leaf = true;firstLevel.children.push(option);});});}});});// 设置已选的value,控件会自动显示对应的名称this.checkedAry = savedValues;
}