实现效果
数据结构
代码部分
选择上一级禁选下一级,同时改变展示区域的tag
<el-cascader
v-model="formValidate.regions"
:props="props2"
:options="options"
clearable
:class="isError ? 'isError' : ''"
@change="handleChangeM"
></el-cascader>
// 禁用标识初始化
changeDisable() {
this.options.forEach((e) => {
e.disabled = false;
//此处也可使用递归处理
if (e.hasOwnProperty('children')) {
e.children.forEach((h) => {
h.disabled = false;
if (h.hasOwnProperty('children')) {
h.children.forEach((k) => {
k.disabled = false;
});
}
});
}
});
},
//改变级联选项时触发的事件
handleChangeM(value) {
this.changeDisable();
//需将选中的下一级禁选,否则展示的下一级仍会存在
value.forEach((e) => {
// 省级选中,市区禁用
if (e.length === 1) {
this.options.forEach((h) => {
if (h.hasOwnProperty('children') && h.value === e[0]) {
h.children.forEach((j) => {
j.disabled = true;
if (j.hasOwnProperty('children')) {
j.children.forEach((k) => {
k.disabled = true;
});
}
});
}
});
}
// 市级选中,区级禁用
if (e.length === 2) {
this.options.forEach((h) => {
if (h.hasOwnProperty('children') && h.value === e[0]) {
h.children.forEach((j) => {
if (j.hasOwnProperty('children') && j.value === e[1]) {
j.children.forEach((k) => {
k.disabled = true;
});
}
});
}
});
}
});
// 省覆盖市,市覆盖区(重点在于处理级联组件上绑定的value值)
for (let i = 0; i < value.length - 1; i++) {
if (value[i].length === 1) {
for (let j = 0; j < value.length; j++) {
if (value[j].length > 1 && value[i][0] === value[j][0]) {
delete value[j];//使用delete并不会移除下标而是将该项设置为undefined,可以避免数组下标变化引起的遍历数组的问题
}
}
}
if (value[i].length === 2) {
for (let j = 0; j < value.length; j++) {
if (value[j].length > 2 && value[i][0] === value[j][0] && value[i][1] === value[j][1]) {
delete value[j];
}
}
}
}
this.$refs.form.validateField('regions', (valid) => {
this.isError = valid;
});
},