ElementUI 级联动态加载及回显
先看图,你是否也遇到这个需求?
如果你正在焦头烂额,无脑抓瞎,那么你来对地方了,因为我将给你一个简单易懂的实现方案。
我也在网上翻了无数页答案,也照着别人的代码和思路尝试了,事实上并不能解决我这个棘手的问题。
级联下拉选多选、懒加载、数据回显,尽管 ElementUI 已经很贴心,文档写的也很好。
前两个很容易就可以实现,可是唯独数据回显被遗忘了,似乎忘记了数据回显应该是级联选择器必备的功能,很遗憾,需要我们自己去实现。
根据文档我们可以很容易配置一个级联组件,并且级联选择器的值应该是一个二维数组。
<el-cascader v-model="updateForm.category" separator="-" :props="cascaderProps" ></el-cascader>
然后配置cascaderProps数据如下
cascaderProps: { multiple: true, checkStrictly: true, lazy: true, lazyLoad: this.lazyLoad, value: "id", label: "name", leaf: "leaf" }
如果照做了,那么恭喜你,已经实现了一半的需求了,不过你很快就会发现,编辑的时候级联选择器的数据是空的。
不过组件给我们提供了一个参数options,如果级联选择的模板是完整的,那就可以很容易回显这个数组,可是现在的选择模板是懒加载的,那么就需要根据updateForm.category 拼出一个备选模板就可以了。
问题的关键就在于options模板如何生成,这个问题困恼了我好几天,最后也是灵感加成,十分钟就撸完了。
先看一段代码,然后分析下思路。
//编辑类目 async updateBtnClick(node, data) { this.node = node.parent; this.updateForm.id = data.id; this.updateForm.name = data.name; this.updateForm.level = ["一级类目", "二级类目", "三级类目", "四级类目"][ node.level - 1 ]; this.updateForm.parent_name = node.level > 1 ? node.parent.data.name : ""; this.updateForm.category = data.category || []; // this.updateForm.category_name = data.category_name || []; this.category_array = Array.from( new Set(this.updateForm.category.join(",").split(",")) ); this.initOptions(); }, //初始化category async initOptions() { let req = { parent_id: 0, category_id: this.node.id || 0 }; let res = await this.$api.getFrontcategoryTemp(req); if (res.error_code == 0 && res.data && res.data.list) { this.cascaderOptions = await this.loadOptions(res.data.list || []); this.updateForm.visible = true; } }, //递归加载子类目 async loadOptions(category) { let array = []; for (let i = 0; i < category.length; i++) { if ( category[i].child_count > 0 && this.category_array.includes(category[i].id + "") ) { let req = { parent_id: category[i].id, category_id: this.node.id || 0 }; let res = await this.$api.getFrontcategoryTemp