我正在尝试将一个数组复制到另一个数组,并将其用作新数组,而不更改旧数组:
<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/
有没有什么办法可以创建基于数组模板的新数组,而无需直接将其绑定到模板?
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?
最满意答案
正如Vue.js文档所说:
在底层,Vue.js附加一个隐藏属性__ob__ , 递归地将对象的可枚举属性转换为getter和setter来启用依赖收集。 以$或_开头的键的属性被跳过。
您可以使用从下划线符号开始的名称来存储模板数组:
data: { testArray: [], _templateArray: [{ name: "TEST" }] }, ready: function() { this.testArray = this.$data._templateArray; }或者你需要它作为Vue.js对象:
this.testArray = JSON.parse(JSON.stringify(this.templateArray));第二种情况对于大数据可能会很慢。
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.
更多推荐
发布评论