- 根据当时修改页面 对Cascader 选择器进行节点的回显遇到的问题
- 所以闲暇整理了一个小demo ,直接上代码里面也都有注释
<template>
<div>
<el-col :span="8">
<el-select v-model="nodeId" placeholder="请选择">
<el-option v-for="item in idOptions" :key="item.id" :label="item.label" :value="item.id"></el-option>
</el-select>
</el-col>
<el-col :span="8">
<el-button type="primary" @click='handleEcho'>编辑页面时的回显当前节点数据</el-button>
</el-col>
<el-col :span="8">
<el-cascader
:options="options"
:show-all-levels="false"
:props="defaultProps"
size="small"
ref="elCascaderOption"
@change="handleOption"
clearable
v-model="form.textOption"
style="width: 100%"
></el-cascader>
</el-col>
</div>
</template>
<script>
export default {
data() {
return {
form: {
textOption: [],
},
defaultProps: {
label: 'label',
value: 'id',
checkStrictly: true,
children: 'children',
},
options: [
{
id: '1',
label: '1-1',
children: [
{
id: '4',
label: '1-1-1',
},
{
id: '5',
label: '1-1-2',
children: [
{
id: '6',
label: '1-1-1-1',
},
],
},
],
},
{
id: '2',
label: '2-1',
children: [
{
id: '7',
label: '2-1-1',
},
],
},
{
id: '3',
label: '3-1',
children: [
{
id: '8',
label: '3-1-1',
},
],
},
],
idOptions: [
{
id: '1',
label: '1-1',
},
{
id: '2',
label: '2-1',
},
{
id: '3',
label: '3-1',
},
{
id: '4',
label: '1-1-1',
},
{
id: '5',
label: '1-1-2',
},
{
id: '6',
label: '1-1-1-1',
},
{
id: '7',
label: '2-1-1',
},
{
id: '8',
label: '3-1-1',
},
],
nodeId: '1',
};
},
mounted() {},
/*
form: {
textOption: [],
},
说明 v-model 绑定的是一个数组
如果传给后端的是一个nodeId, 那么回显的时候在数组里面传 [父节点所有id,nodeId]
例:显示节点 label: label: '1-1-1-1',, id: 6
那么form.textOption = [1,5,6]
*/
methods: {
handleOption() {
// 获取当前节点选择的id
let node = this.$refs.elCascaderOption.getCheckedNodes()
/**
* @param nodeId: 传到后端的id
*/
this.nodeId = node[0].data.id
// console.log(this.$refs.elCascaderOption.getCheckedNodes());
},
handleEcho() {
let arrParentsId = [] // 接受返回的所有父级id
arrParentsId = this.getParentIds(this.nodeId, this.options)
/*
这一步是返回父级id的基础上在数组的末尾加上当前节点的id
这样在回显时显示的是当前节点
*/
arrParentsId.push(this.nodeId)
this.form.textOption = arrParentsId
},
// 获取当前选中节点的所有上级父节点
getParentIds(id, data) {
// 深度遍历查找
function dfs(data, id, parents) {
for(var i = 0;i<data.length;i++) {
var item = data[i];
// 找到id则返回父级id
if(item.id === id) return parents;
// children不存在或为空则不递归
if(!item.children || !item.children.length) continue;
// 往下查找时将当前id入栈
parents.push(item.id);
if(dfs(item.children, id, parents).length ) return parents;
// 深度遍历查找未找到时当前id 出栈
parents.pop()
}
// 未找到时返回空数组
return [];
}
return dfs(data, id, []);
},
},
};
</script>
<style>
</style>
下面可以直接复制 当成一个组件用来查看一下效果哦~~
有什么好的方法或者不对的可以指出 相互学习哦