最近做一个后台管理系统菜单权限控制,选择菜单用到了element-ui 的组件el-cascader,只保存了最后一级菜单的id,编辑回显的时候就显示出了问题,回显一直是错的,在网上搜索了很久没找到合适的,自己写了一个,记录一下。
<el-form-item label="上级菜单" prop="pid">
<el-cascader ref="selectMenu" :options="selectTableData"
:props="{ value: 'id', label: 'menu_name', children: 'children', checkStrictly: true, emitPath:false }"
clearable @change="onSelectPMenu" v-model="selectMenu"></el-cascader>
</el-form-item>
export default {
data() {
return {
selectMenu: [0],
selectTableData: [],
formData: {
pid: 0,
}
}
},
methods: {
// 回显菜单
getPidMenuList(pid) {
let cid_list = [];
this.selectTableData.forEach((item, index) => {
if (item.id == pid) {
cid_list = [item.id];
return false;
} else {
if (item.children) {
let newCid_list = [item.id];
let list = nodefun(item.children, pid, newCid_list);
if (list) {
cid_list = list;
}
}
}
});
// 递归函数
function nodefun(newVal, newId, newCid_list) {
let flag = false;
newVal.forEach((j) => {
if (j.id == newId) {
newCid_list.push(j.id);
flag = true;
} else {
if (j.children) {
let cid_list = JSON.parse(JSON.stringify(newCid_list));
cid_list.push(j.id);
let list = nodefun(j.children, newId, cid_list);
if (list) {
newCid_list = list;
flag = true;
}
}
}
});
if (flag) {
return newCid_list;
}
}
return cid_list;
},
onSelectPMenu(e) {
console.log(e)
this.formData.pid = e[0]
this.$refs.selectMenu.dropDownVisible = false
},
onEdit(row) {
this.selectMenu = this.getPidMenuList(row.pid)
}
}
```