How to decouple a copy of an array in Vue.js
I am trying to copy one array to another and use it as a new array without any changes to the 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 problem is then i update the new testArray. I am also changing the old templateArray.
script in action: https://jsfiddle.net/4po1cpkp/7/
Is there a way to create a new array based on an array template without directly binding it to the template?
source to share
As the Vue.js documentation says:
Under the hood, Vue.js attaches a hidden property
__ob__
and recursively converts enumerated property objects to getters and setters to provide dependency collection. Properties with keys that start with $ or _.
You can store an array of templates with a name starting with an underscore:
data: {
testArray: [],
_templateArray: [{ name: "TEST" }]
},
ready: function() {
this.testArray = this.$data._templateArray;
}
Or you, if you need it as a Vue.js object:
this.testArray = JSON.parse(JSON.stringify(this.templateArray));
The second case can be slow for big data.
source to share
You can use slice()
Array prototype in more detail at MDN Array.prototype.slice ()
this.testArray = [].slice.call(this.templateArray)
source to share