Our company needs to implement a way to obtain provincial information first, and then obtain city-level information through the province, and so on. Then we can use the dynamic loading in the cascader cascade selector in the element UI , and here is the solution to the problem of incomplete clearing
The effect is as follows:
Not much to say, just go to the code
in html
<el-cascader
v-if="isShowAddressInfo"
ref="addressRef"
v-model="address"
:props="cascaderProps"
@change="visibleChange"
:show-all-levels="true" //回显完整的地址,false则只回显镇
size="small"
clearable
/>
js
//computed 里面
computed: {
cascaderProps() {
return {
lazy: true,
lazyLoad: this.lazyLoad,
}
},
},
// method里面
methods: {
visibleChange() {
// 当使用clearable清空的时候,只能清空搜索栏里的内容,但不能使下拉框中的内容也恢复成初始,因此需要ref
if (this.address.length === 0) {
let codeRef = this.$refs.addressRef
codeRef.panel.activePath = []
codeRef.panel.loadCount = 0
codeRef.panel.lazyLoad()
}
},
async lazyLoad(node, resolve) {
let level = node.level
let result
switch (level) {
case 0: // 类型
let initRes = await getAdressCode()
result = initRes.data
result.forEach((item) => {
item.value = item.divisionCode
item.label = item.divisionName
})
// result = [
// { value: '北京', label: '111' },
// { value: '上海', label: '222' },
// { value: '深圳', label: '333' },
// ]
break
case 1: //一级目录
let firstParams = {
provinceCode: node.data.value
}
let firstRes = await getAdressCode(firstParams)
result = firstRes.data
result.forEach((item) => {
item.value = item.divisionCode
item.label = item.divisionName
})
break
case 2: // 二级目录
let secondParams = {
cityCode: node.data.value
}
let secondRes = await getAdressCode(secondParams)
result = secondRes.data
result.forEach((item) => {
item.value = item.divisionCode
item.label = item.divisionName
})
break
case 3:
// 三级目录
let thirdParams = {
areaCode: node.data.value,
}
let thirdRes = await getAdressCode(thirdParams)
result = thirdRes.data
result.forEach((item) => {
item.value = item.divisionCode
item.label = item.divisionName
item.leaf = level >= 3
})
break
default:
result = []
break
}
resolve(result)
},