javascript - 如何在 Vue.js 中取消绑定(bind)数组副本

标签 javascript arrays 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/

有没有什么方法可以在不直接绑定(bind)到模板的情况下基于数组模板创建新数组?

最佳答案

正如 Vue.js 文档所说:

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.

您可以存储名称以下划线开头的模板数组:

  data: {
      testArray: [],
      _templateArray: [{ name: "TEST" }]
  },
  ready: function() {
      this.testArray = this.$data._templateArray;
  }

或者如果您需要它作为 Vue.js 对象:

this.testArray = JSON.parse(JSON.stringify(this.templateArray));

第二种情况对于大数据来说可能会很慢。

关于javascript - 如何在 Vue.js 中取消绑定(bind)数组副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31344041/

相关文章:

javascript - vue中的v-bind是什么

vue.js - 如何将 ASP Core Web API VueJS 站点部署到 IIS

javascript - 为什么列表元素无法使用显示初始正确显示

javascript - 如何使用本地存储在刷新时保存当前选项卡

c - sizeof(table)/sizof(table[0]) 不起作用

arrays - 如何使用where子句检查postgres数组中是否存在值

python - 在 python 列表理解中评估 True 和 False 的条件?

javascript - AngularJs 路由模块没有重定向到另一个页面

javascript - 即使行被删除,备用表行颜色

javascript - 在 Vue 中以编程方式更改自动完成所选项目