el-cascader级联组件允许选择任意一级
实例场景:
父级类目数据动态加载,允许选择任意一级,选中后父级编码联动
实现方式
1、template部分
<
el-cascader
ref=
"elcascader"
placeholder=
"请选择父级类目"
v-model="
form.
ParentGuids"
:
options="
options"
@
change="
handleChange"
:
props="
optionProps"
clearable
filterable
:
show-all-levels="
false"
:
change-on-select="
true"
></
el-cascader
>
2、data部分
options: [], // 待选数据
optionProps: {
multiple:
false, // 是否可以多选
checkStrictly:
true, // 是否可以选择任意一级
label:
'catalogName',
value:
'id',
children:
'children',
},
parentGuid:
'',
3、methods部分
// 获取待选数据
GetTreeData() {
this.
$api.
DataManagement.
GetTree().
then((
res)
=> {
if (
res.
status.
code ==
200) {
this.
options =
this.
setTreeData(
res.
result);
}
});
},
当待选数据的children是空数组时,前端需要处理一下数据,否则页面会出现一个层级是空的情况
setTreeData(
data) {
data.
forEach((
item)
=> {
if (
item.
children.
length <
1) {
item.
children =
undefined;
}
else {
this.
setTreeData(
item.
children);
}
});
return
data;
},
// 父级类目 级联的改变事件
handleChange() {
if (
this.
form.
ParentGuids) {
this.
ParentGuids =
this.
form.
ParentGuids[
this.
form.
ParentGuids.
length -
1];
this.
findParentCode(
this.
options);
// 根据选中的父级类目找出父级编码
}
else {
this.
form.
ParentGuids = [];
}
this.
$refs.
elcascader.
dropDownVisible =
false;
// 根据选中的父级类目找出父级编码
},
findParentCode(
data) {
data.
forEach((
item)
=> {
if (
item.
id ==
this.
ParentGuids) {
this.
form.
parentCode =
item.
catalogCode;
// 找到父级编码然后赋值
return;
}
if (
item.
children) {
this.
findParentCode(
item.
children);
}
else {
if (
item.
id ==
this.
ParentGuids) {
this.
form.
parentCode =
item.
catalogCode;
return;
}
}
});
},
好了,到这功能就已经完成了,看看效果吧