Laj*_*rek 8 javascript json copy reference vue.js
在我的组件中,我声明了一些这样的数据:
data() {
return {
defaultValue: {json object with some structure},
activeValue: {}
...
Run Code Online (Sandbox Code Playgroud)
在组件方法中,make 复制此值:
this.activeValue = this.defaultValue
Run Code Online (Sandbox Code Playgroud)
但问题是,在更改this.activeValue值之后,a 也发生了变化this.defaultValue。
如果我使用Object.freeze(this.defaultValue)并尝试更改,this.activeValue则会出现错误 - 对象不可写。
我如何复制数据但没有参考?
如果你有简单的对象,最快最简单的方法就是使用 JSON.parse 和 JSON.stringify;
const obj = {};
const objNoReference = JSON.parse(JSON.stringify(obj));
Run Code Online (Sandbox Code Playgroud)
this.activeValue = { ...this.defaultValue }
Run Code Online (Sandbox Code Playgroud)
如果您没有嵌套对象,使用 ES6 扩展运算符将帮助您进行复制。如果使用等号 = 进行相等,则不会创建新对象,而只会创建一个引用当前对象的变量(如浅表副本)。
要进行完整的深复制,即使它是嵌套对象,也可以这样做:
const objNoReference = JSON.parse(JSON.stringify(obj));
Run Code Online (Sandbox Code Playgroud)
正如猫头鹰建议的那样。
JSON.stringify 比使用 JSON.parse 更好的方法是:
this.activeValue = {...this.defaultValue}
Run Code Online (Sandbox Code Playgroud)
但这并不被某些浏览器(IE)原生支持,除非与转译器(babel)一起使用
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
更新
考虑到你最初的问题是关于 Vue 中的一种方法,vue 中还有一个本机方法:
this.activeValue = Vue.util.extend({}, this.defaultValue)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!