VUE爬坑:把对象中的数据给了某个变量,改变一个对象的值,另一个对象也变化的解决办法!

在vue中,在data里建立两个对象。

data() {
    return {
      dataA:{
        a:1
      },
      dataB:'' 
    }
};

将dataA的内容赋值给dataB,改变dataB里对象的值,发现dataA里的值也跟着变化了。为什么会出现这种情况呢?其实,这是一个引用传递而不是值传递,dataA和dataB指向的是同一个内存地址。

this.dataB = this.dataA;
this.dataB.a = 5;
console.log( this.dataA.a);//返回5
console.log( this.dataB.a);//返回5

如果我们不想让dataA的值跟着联动变化,应该怎么做呢?可以先把dataA转换成字符串,然后在转换成对象,代码如下:

this.dataB = JSON.parse(JSON.stringify(this.dataA));
this.dataB.a = 5;
console.log( this.dataA.a);//返回1
console.log( this.dataB.a);//返回5

猜你喜欢

转载自blog.csdn.net/jiangwei1994/article/details/83068944