javascript 如何在 Vue.js 中取消绑定数组副本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31344041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unbind an array copy in Vue.js
提问by Vaidas
I am trying to copy one array to another and use this like the new array without any changes to old one:
我试图将一个数组复制到另一个数组,并像使用新数组一样使用它,而不对旧数组进行任何更改:
<div id="app">
<div class="form-group">
<label>Test input</label>
<input v-model="testArray[0].name" type="text" class="form-control" placeholder="Input">
</div>
<br>
<pre>testArray: {{ testArray[0] | json}}</pre>
<pre>templateArray: {{ templateArray[0] | json }}</pre>
new Vue({
el: '#app',
data: {
testArray: [],
templateArray: [{name: "TEST"},],
},
ready: function() {
this.testArray = this.templateArray.slice(0);
},
});
the issue is that then I am updating new array 'testArray' I also change old array 'templateArray'.
问题是然后我更新新数组'testArray'我也改变了旧数组'templateArray'。
The script in action: https://jsfiddle.net/4po1cpkp/7/
运行中的脚本:https: //jsfiddle.net/4po1cpkp/7/
Is there any way to create new array based on array template without directly binding it to template?
有什么方法可以根据数组模板创建新数组而不直接将其绑定到模板?
回答by Andrey Etumyan
As Vue.js documentation says:
正如 Vue.js 文档所说:
Under the hood, Vue.js attaches a hidden property
__ob__
and recursivelyconverts the object's enumerable properties into getters and setters to enable dependency collection. Properties with keys that starts with $ or _ are skipped.
在幕后,Vue.js 附加了一个隐藏属性
__ob__
并 递归地将对象的可枚举属性转换为 getter 和 setter 以启用依赖项收集。键以 $ 或 _ 开头的属性将被跳过。
You can store your template array with name started from underscore sign:
您可以使用以下划线符号开头的名称存储模板数组:
data: {
testArray: [],
_templateArray: [{ name: "TEST" }]
},
ready: function() {
this.testArray = this.$data._templateArray;
}
Or you if need it as a Vue.js object:
或者你需要它作为 Vue.js 对象:
this.testArray = JSON.parse(JSON.stringify(this.templateArray));
The second case might be slow for big data.
对于大数据,第二种情况可能会很慢。
回答by Nisal Gunawardana
I used Vue extend function Vue.util.extend to copy array with un-binding in Vue 2:
我在 Vue 2 中使用了 Vue 扩展函数 Vue.util.extend 来复制数组并取消绑定:
this.items_list.push(Vue.util.extend({}, this.list_item));
回答by tunnes
You can use slice()
of array prototype read more in MDN Array.prototype.slice()
您可以slice()
在MDN Array.prototype.slice() 中使用数组原型阅读更多内容
this.testArray = [].slice.call(this.templateArray)
this.testArray = [].slice.call(this.templateArray)