如何解除Vue.js中的数组副本(How to unbind an array copy in Vue.js)

编程入门 行业动态 更新时间:2024-10-24 20:13:15
如何解除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/

有没有什么办法可以创建基于数组模板的新数组,而无需直接将其绑定到模板?

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.

更多推荐

本文发布于:2023-08-05 04:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1428531.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   副本   js   Vue   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!