问题描述
在做项目的时候遇到自定义下拉列表多选组件点击下拉后无法缩回的问题,在本地运行代码,没有任何问题,但是部署到测试环境或生产环境时,在360浏览器上正常,在谷歌浏览器、Edge上就会出现下拉无法缩回的问题,同时可以看到测试环境或生产环境报错了。
报错信息如下
Uncaugnt TypeError: Cannot read properties of undefined (reading 'includes') at o.handleClick.
翻译:无法读取o.handleClick处未定义(读取“includes”)的属性。
原因分析
经过排查发现是组件的下面这段代码中 e
在本地和测试环境中打印出来的信息并不一致,测试环境打印出来的 e
没有 path
这个属性。
解决方法
libs/util.js
中代码:
export composedPath = e => {
// 存在则直接return
if (e.path) {
return e.path
}
// 不存在则遍历target节点
let target = e.target
e.path = []
while (target.parentNode !== null) {
e.path.push(target)
target = target.parentNode
}
// 最后补上document和window
e.path.push(document, window)
return e.path
}
组件中代码:
import { composedPath } from "@/libs/util";
handleClick(e) {
let arr = composedPath(e) || []
// if (e && e.path.includes(this.$el)) {
if (arr.length && arr.includes(this.$el)) {
this.clickPosFlag = true
} else {
this.clickPosFlag = false
this.onInputBlur()
}
},