1 问题描述
自定义 el-select
的 change
事件后,el-select
显示出现异常,经过打印发现 data.carLocationList 列表中值随着选择不同的 el-option
发送改变的问题,同时导致 el-select
显示异常。
const handleSelectChange = (val: string) => {
for (let index = 0; index < data.carLocationList.length; index++) {
let element = data.carLocationList[index]
if (element.carCode === val) {
data.selectedCarLocation = element
}
}
}
2 引发原因
data.carLocationList[index]
是一个对象,在利用 = 赋值时,待赋值的变量会得到对象的内存地址,即浅拷贝了对象。后面对该变量进行修改操作时,也会同时修改 data.carLocationList[index]
的值,因此出现 el-select
显示异常的问题。
3 解决方法
利用 JSON.stringfy()
将对象先转化为字符串,然后利用 JSON.parse()
转化为新的对象,将新的对象再用 = 赋值给要赋值的变量即可。
在 if 语句中利用 = 赋值前添加如下代码:
element = JSON.parse(JSON.stringify(element))