我有一个Vue.js应用程序,我在一系列项目上有一个v形重复.我想在项目列表中添加一个新项目.当我try this.items.push(this.newItem)次时,推送的对象仍然绑定到输入.考虑下面的内容:

new Vue({
  el: '#demo',

  data: {
    items: [
      {
        start: '12:15',
        end: '13:15',
        name: 'Whatch Vue.js Laracast',
        description: 'Watched the Laracast series on Vue.js',
        tags: ['learning', 'Vue.js', 'Laracast', 'PHP'],
        note: "Vue.js is really awesome. Thanks Evan You!!!"
      },
      {
        start: '13:15',
        end: '13:30',
        name: "Rubik's Cube",
        description: "Play with my Rubik's Cube",
        tags: ['Logic', 'Puzzle', "Rubik's Cube"],
        note: "Learned a new algorithm."
      }
    ],
    newItem: {start: '', end: '', name: '', description: '', tags: '', note: ''}
  },

  methods: {
    addItem: function(e) {
      e.preventDefault();

      this.items.push(this.newItem);
    }
  }
});

如上所述,将把绑定到items数组的对象推送到items数组上.问题是我只想要一个对象的副本,这样当输入改变时它就不会再改变了.看这个this fiddle.我知道我能做到:

addItem: function(e) {
  e.preventDefault();
  this.items.push({
    name:        this.newItem.name,
    start:       this.newItem.start,
    end:         this.newItem.end,
    description: this.newItem.description,
    tags:        this.newItem.tags,
    notes:       this.newItem.notes
  })
}

This works但这是很多重复.

The question:.是否有一种内置方法,可以只添加对象的副本,而不是持久对象.

推荐答案

参见GitHub上的this issue.

Shallow Clone

我一直在使用jQuery的$.extend,直到Evan You指出有一个未经证明的Build-it extend函数Vue.util.extend可以进行浅层克隆.所以你可以使用的是:

addItem: function(e) {
  e.preventDefault();

  this.items.push(Vue.util.extend({}, this.newItem));
}

updated Fiddle.

Deep Clone

在引用其他对象的对象上执行浅克隆时,将引用复制到外部对象,而不是克隆它们.要完全克隆对象,请执行Deep Clone.

对于深度克隆,按照埃文在第一个链接中的建议,可以使用:JSON.parse(JSON.stringify(object)).这可以在this fiddlethis fiddle之间看到.

如果使用lodash,请查看lodash cloneDeep.如果使用NPM,请查看clone-deep.

Vue.js相关问答推荐

无法从CDN使用Vue和PrimeVue呈现DataTable

作为props 传递的原始 ref 的 Vue 3 react 性

在 Ajax 函数中访问 Vue.js 组件属性

无需直接 DOM 操作即可绘制d3-axis

确保在渲染组件之前加载 Vuex 状态

CLI 3 - 如何为 CSS/Sass 创建vendor bundle ?

Vuetify 容器不会填充高度

Vuetify v-select 组件宽度变化

使用 vue-property-decorator 时注册本地组件

vuejs中通过变量动态调用方法

Vue.js 如果在视图中

包含 Vue 组件的 HTML 字符串的 Nuxt 渲染函数

为什么 v-model 不适用于数组和 v-for 循环?

如何在 vuetify 中将工具提示添加到数据表标题?

有没有办法知道组件实例何时挂载?

如何在 Vuetify DataTable 组件中设置初始每页行数值?

IOS在输入焦点上显示键盘

表格行上的 Vuejs 转换

如何在 Vue.js 2 应用程序中模拟 onbeforeunload?

Vue-meta:metaInfo 无权访问计算(computed)属性