<el-form-item label="章節" style="margin-right: 64px"> <el-cascader ref="cascader" :value="contentChascascader" //是數組,存的是當前數據的value。一般是多個值 :props="this.$store.state.selectorMod.cascaderProps" :options="this.$store.state.selectorMod.contentChas" //渲染數據 :show-all-levels="false" //輸入框中不顯示選中值的完整路徑 :change-on-select="true" @change="handleContentChaChange" style="margin-bottom: 10px;width: 240px;" > </el-cascader> </el-form-item>
我遇到的問題:當進入到編輯頁面時,后台傳來的只有最后一級的id,也就是說value數組里存的只有一個數,沒有父級的id。這就導致無法在選框中顯示出來label
解決辦法:因為可以從后台獲取到整個數據結構,發現子對象都有parentId這個屬性,所以編寫了getCascaderObj方法手動獲取級聯id。
思想:拿到value值,遍歷options
getCascaderObj(val,opt) { var thisVue=this return val.map(function (value) { for (var itm of opt) { if (itm.id == value) { // console.log("成功匹配") thisVue.chapterArr.unshift(itm.id) // console.log("第二步找父級。。。") // console.log("parentId:"+itm.parentId) thisVue.getCascaderObj([itm.parentId],thisVue.$store.state.selectorMod.contentChas) return }else{ if(thisVue.isHasChid(itm)){ thisVue.getCascaderObj(val,itm.childs) } } } return null; }); },
注意:上述方法中的參數val應該是一個數組。
另:
給 cascader 組件一個別名,然后用 this.$refs[關聯組件名].currentLabels 就能取到選中的 labels