问题场景
笔者项目中的地址选择是使用Elementui的Cascader来实现的如果是正常的用户选择还好,会选择到最后一级,但是如果地址信息是通过第三方平台通过来的且与本系统地址库不对应则需要做映射(跨平台同步地址库的心酸大家应该都懂)。有的平台地址本身就有问题,比如地区项只有到一级/二级这总情况就会显示空白。
比如这个地址,信都区下面还有一级,但是因为不是叶子节点,所以显示空白
问题原因
既然知道问题了,我们来分析一下原因所在。通过定位ElementUI源码找到关键代码
就是这句if (node && (config.checkStrictly || node.isLeaf)) 导致
解决方案
既然找到问题代码,那么解决方案就来了。一下有两个
- 打开cascader的checkStrictly属性,但是注意关注checkStrictly的作用
- 自己在$nextTick渲染后在去改变Cacader组件的presentText值
因为我项目中的地址选择是通过懒加载请求的后端,所以我在拿到地址数据后添加了一段来解决
解释:关于什么是用setTimeout,我这里是为了确保在$nextTick只后执行这段代码,至于为什么请转至使用Vue的nextTick引发的执行顺序之争(转载)
寻找答案,笔者不是专业前端。
组件源码
<!-- 地址选则组件 -->
<template>
<el-cascader
ref="area"
v-model="selectVal"
v-loading="loading"
:options="options"
:props="props"
:disabled="disabled"
clearable
:emit-path="false"
@change="changeNode"
/>
</template>
<script>
import { getByParent, getByPath } from '@/api/basic/area'
export default {
name: 'AreaSelect',
props: {
value: {},
disabled: {
type: Boolean,
default: false
}
},
data() {
return {
selectVal: null,
loading: false,
props: {
lazy: true,
value: 'id',
label: 'name',
leaf: 'leaf',
lazyLoad(node, resolve) {
getByParent(node.value).then((response) => {
const {data} = response
resolve(data)
})
}
},
options: []
}
},
watch: {
value(value, oldValue) {
// 保证实时刷新(临时处理方案)
if (Array.isArray(this.selectVal)) {
this.selectVal = value
return
}
this.selectVal = value
this.getByPath()
}
},
created() {
this.selectVal = this.value
this.getByPath()
},
computed:{
area() {
return this.$refs.area;
},
},
methods: {
changeNode(nodeVal) {
const areaId = nodeVal[nodeVal.length - 1]
this.$emit('input', areaId)
this.$emit('change', areaId, nodeVal)
},
getByPath() {
if (this.selectVal == null) {
return
}
this.loading = true
getByPath(this.selectVal).then((response) => {
const { data } = response
this.options = data
setTimeout(() => {
// 设置显示文本
if (this.value && !this.area.presentText) {
const node = this.area.panel.getNodeByValue(this.value);
if (node) {
this.area.presentText = node.getText(this.area.showAllLevels, this.area.separator)
}
}
}, 0);
}).finally(() => {
this.loading = false
this.$emit('change', this.selectVal)
})
},
// 选中某个值
selected(value) {
this.selectVal = value
this.getByPath()
}
}
}
</script>