在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
5978

被折叠的 条评论
为什么被折叠?



