1. 问题
今天收到一个bug,el-cascader的值匹配不上options时,选择框什么都不显示,容易误导用户
2. 解决过程
有什么办法可以让我们传一个参数进去,匹配不上的时候就用这个我们传进去的参数,首先查看官方文档发现了它支持插槽
事情总不是一帆风顺的,写出来的效果是在filterable匹配不上的时候显示的内容
事到如今那就只能看源码了,这里大概就是初始化的时候去匹配
找到了这里,就有灵感了,根据抖音里山哥重写组件的操作,我可以新写一个组件,然后继承el-cascader,之后重写它的computePresentText方法,重写之后的新组件如下
<script>
import { Cascader } from 'element-ui'
export default {
extends: Cascader,
props: {
mmEmpty: {
type: String,
default: '',
},
},
methods: {
handleClear() {
this.presentText = ''
this.panel.clearCheckedNodes()
},
computePresentText() {
const { checkedValue, config } = this
console.log(checkedValue)
if (!this.isEmptyValue(checkedValue)) {
const node = this.panel.getNodeByValue(checkedValue)
if (node && (config.checkStrictly || node.isLeaf)) {
this.presentText = node.getText(this.showAllLevels, this.separator)
return
} else if (this.mmEmpty) {
this.presentText = this.mmEmpty
return
}
}
this.presentText = null
},
},
}
</script>
3. 总结
这样写目前只是解决单选时候的问题,多选情况源码由于是展示el-tag会牵涉到节点操作,还没有去仔细研究,如果有大佬有解决办法,请不吝赐教