效果图:
代码如下:
<el-form-item label="父级菜单" prop="PerParentID">
<el-select
ref="selectTree"
v-model="form.PerParentID"
placeholder="请选择父级菜单"
style="width:100%"
clearable
>
<el-option
:key="pidTemp.id"
:value="pidTemp.id"
:label="pidTemp.name"
style="height:150px;overflow: auto;background-color:#fff"
>
<el-tree
node-key="id"
:data="treeData"
:props="defaultProps1"
@node-click="handleNodeClick"
></el-tree>
</el-option>
</el-select>
</el-form-item>
data() {
return {
// 存放树形的源数据
form: {
PerID: "",
PerParentID: "",
PerType: 1,
PerName: "",
PerUrl: "",
PerIcon: "",
IsOpen: true,
PerIsOpen: "",
OrderNo: 0,
Remark: ""
},
// 树形对应
defaultProps1: {
children: "children", //子菜单不叫children在这里改
label: "name"
},
treeData: [], //接收后台数据
// 选中一条数据的name和id,给值 el-option
pidTemp: {
pid: "11",
name: "1"
},
}
},
// 获取数据
getdata() {
ModuleList()
.then(res => {
console.log(res);
this.treeData = []; //接收后台数据
let nodeArry = []; //声明用来接收一级菜单
let treeArry = res.data;
treeArry.forEach(function(val, index, arr) {
//遍历数组
var firstNode = val;
var seq = index;
var secondNode = arr;
var secondArry = []; //声明用来接收二级菜单
if (firstNode.Children != null && firstNode.Children.length > 0) {
//判断一级菜单有无子菜单
firstNode.Children.forEach(function(val2, index2, arr2) {
//遍历一级菜单
var sencodNode = val2; //接收遍历完的的二级菜单
var thirdArry = []; //声明用来接收三级菜单
if (
sencodNode.Children != null &&
sencodNode.Children.length > 0
) {
//判断二级有无子菜单
sencodNode.Children.forEach(function(val3, index3, arr3) {
//遍历二级菜单
var thirdNode = val3; //接收遍历完的三级菜单
var jsonNode3 = {
//创建三级菜单模版
id: thirdNode.PerID,
pId: 0,
Perid: thirdNode.PerParentID,
name: thirdNode.PerName,
open: true,
sencodNode: false,
children: null
};
thirdArry.push(jsonNode3); //thirdArry push 三级菜单列表
});
}
var jsonNode2 = {
//创建二级菜单模版
id: sencodNode.PerID,
pId: 0,
Perid: sencodNode.PerParentID,
name: sencodNode.PerName,
open: true,
sencodNode: false,
children: thirdArry // children (thirdArry)导入三级菜单列表
};
secondArry.push(jsonNode2); //secondArry push 二级菜单列表
});
}
var jsonNode = {
//创建一级菜单模版
id: firstNode.PerID,
pId: 0,
Perid: firstNode.PerParentID,
name: firstNode.PerName,
open: true,
checked: false,
children: secondArry // children (secondArry)导入二级菜单列表
};
nodeArry.push(jsonNode); //nodeArry push 二级菜单列表
});
this.treeData = nodeArry;
})
.catch(err => {
this.loading = false;
this.$message.error("菜单管理列表失败,请稍后再试!");
});
},
// 树形下拉点击调用
handleNodeClick(data) {
console.log(data);
this.pidTemp.id = data.id; //赋值
this.pidTemp.name = data.name; //赋值
this.$refs.selectTree.blur(); //选中后关闭
},
有不理解或者更好的创意可以随时交流呦