vue开发过程中数组新push一个对象,其他对象同时被修改

		this.targetData.push(item)
		
		原因:vue开发数组push一条对象而导致之前push进去的对象也变成后面进去对象的值,百度发现原因是对象
	是引用类型,传递的是引用地址,所以两个数组引用的是同一个对象,只要其中一个数组改变,就会导
	致对象改变,进而另一个引用的数组也会改。
	
		解决方法:将需要放入数组的对象先深拷贝一份,用拷贝的对象,这样就不存在引用关系了。
	
	1. 拷贝方式一:Object.assign({
    
    },需要拷贝的对象)
		eg:const target = {
    
     x: 1 };
			const content1= {
    
     m: 2 };
			const content2= {
    
     l: 3 };
			Object.assign(target,content1,content2);
			Object.assign方法中第一个参数是目标对象,之后的参数全都是源对象。
			结果:target // {x:1, m:2, l:3}
			
	   拷贝方式二:JSON.parse(JSON.stringify(需要拷贝的对象)) 
	   	eg:this.targetData = JSON.parse(JSON.stringify(this.targetDataPar))
	   	
	2. 重新申请一个内存空间,然后赋值给他,再push,实现深拷贝
        eg:let obj={
    
                            
            id: this.randomArr(200, 0, 500),                        
            key: this.originalCheckedData[index].key,                       
            label: this.originalCheckedData[index].label,                   
        }                   
        this.targetData.push(obj)    

在使用vue框架开发时,遇到一个数组push一条对象而导致之前push进去的对象也变成后面进去对象的值。后来发现是因为push对象时,指针一直指向的是之前输入框绑定的对象地址,所以输入框下次输入时值改变,数组内的值也就变了。

	remark_formInline: {
    
    
        name: '',
        type: 'IT反馈',
        creator: 'admin',
        time: '' ,
        account:''
        }
	this.remark_datas.push(this.remark_formInline);
	//按上面这种写法直接push进去,数组内的值会跟着变化。


需要重新申请一个内存空间,然后赋值给他,再push,实现深拷贝。
    let obj={
    
    
 		id: Object.keys(this.addDirectoryList.directoryRemark.remark_datas),
 		name: this.remark_formInline.name,
 		type: this.remark_formInline.type,
 		creator: this.remark_formInline.creator,
 		time: this.remark_formInline.time,
 		account: this.remark_formInline.account,
 	}
 	this.remark_datas.push(obj);

猜你喜欢

转载自blog.csdn.net/Sunshine_GirlXue/article/details/115024772