如何在Vue.js中解除绑定数组副本 [英] How to unbind an array copy in Vue.js
问题描述
我正在尝试将一个数组复制到另一个数组,并像使用新数组一样使用它,而无需对旧数组进行任何更改:
<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);
},
});
问题是,然后我要更新新的数组'testArray',我还要更改旧的数组'templateArray'.
正在运行的脚本: https://jsfiddle.net/4po1cpkp/7/ >
有什么方法可以在不将模板直接绑定到模板的情况下基于数组模板创建新数组吗?
如Vue.js文档所述:
在引擎盖下,Vue.js附加了一个隐藏属性
__ob__
, 递归将对象的可枚举属性转换为吸气剂 和setter以启用依赖项收集.具有以下属性的键 以$或_开头的内容将被跳过.
您可以将模板数组的名称以下划线符号开头:
data: {
testArray: [],
_templateArray: [{ name: "TEST" }]
},
ready: function() {
this.testArray = this.$data._templateArray;
}
或者您是否需要将其作为Vue.js对象:
this.testArray = JSON.parse(JSON.stringify(this.templateArray));
对于大数据,第二种情况可能会变慢.
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'.
The script in action: https://jsfiddle.net/4po1cpkp/7/
Is there any way to create new array based on array template without directly binding it to template?
As Vue.js documentation says:
Under the hood, Vue.js attaches a hidden property
__ob__
and recursively converts the object’s enumerable properties into getters and setters to enable dependency collection. Properties with keys that starts with $ or _ are skipped.
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:
this.testArray = JSON.parse(JSON.stringify(this.templateArray));
The second case might be slow for big data.
这篇关于如何在Vue.js中解除绑定数组副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!