1、首先进入显示代码
<el-form-item label="行政区划" prop="areaCode">
<el-cascader
ref="cascader"
:props="defaultParams"
:options="options"
v-model="areaCodeList"
:show-all-levels="true"
:filterable="true"
:clearable="true"
></el-cascader>
</el-form-item>
2、其次定义变量初始化
// 级联
options: [],
selectedOptions: [],
defaultParams: {
label: "name",
value: "code",
children: "children",
checkStrictly: true,
},
areaCodeList: [],
3、执行listArea显示数据并赋值
created() {
// 获取行政区划
this.loading = true;
listArea(330000).then((response) => {
this.options = this.getTreeData(response);
this.loading = false;
});
},
// 监听,当点击按钮时关闭下拉
watch: {
areaCodeList() {
if (this.$refs.cascader) {
this.$refs.cascader.dropDownVisible = false;
}
},
},
//点击级联文字实现选中效果
mounted() {
//点击文本就让它自动点击前面的input就可以触发选择。但是因组件阻止了冒泡,暂时想不到好方法来触发。
//这种比较耗性能,暂时想不到其他的,能实现效果了。
setInterval(function () {
document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
el.onclick = function () {
if (this.previousElementSibling) this.previousElementSibling.click();
};
});
}, 1000);
},
methods: {
// 递归
getTreeData(data) {
// 循环遍历json数据
for (var i = 0; i < data.length; i++) {
if (data[i].children.length < 1) {
// children若为空数组,则将children设为undefined
data[i].children = null;
} else {
// children若不为空数组,则继续 递归调用 本方法
this.getTreeData(data[i].children);
}
}
return data;
}
}
5、显示效果如下