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