简体   繁体   English

Vue.js 2:从数据对象中删除属性

[英]Vue.js 2: Delete property from data object

How can you delete a property/key from a Vue.js data object (ie associative array) like this:如何从 Vue.js 数据对象(即关联数组)中删除属性/键,如下所示:

var vm = new Vue({
    data: {
        users: {
            foo : { firstName: ..., lastName: ... },
            bar : { firstName: ..., lastName: ... }
        }
    },
    methods: {
        someFunction : function ()
        {
            // how to remove `users.foo`?
        }
    }
});

Googling around, I found these two ways, but both don't work:谷歌搜索,我找到了这两种方法,但都不起作用:

  • delete this.users.foo; is not updating the DOM没有更新 DOM
  • this.users.splice('foo', 1); is not working at all (probably only works on arrays, not on objects)根本不起作用(可能仅适用于数组,不适用于对象)

The answer is:答案是:

Vue.delete(users, 'foo');

It took me a while to find it, that's why I'm posting it here ;-)我花了一段时间才找到它,这就是我在这里发布它的原因;-)
https://github.com/vuejs/vue/issues/3368#issuecomment-236642919 https://github.com/vuejs/vue/issues/3368#issuecomment-236642919

It's important to know that vm.$delete is a alias for Vue.delete and if you try something like this.delete() you will get a error.重要的是要知道vm.$deleteVue.delete的别名,如果你尝试类似this.delete()你会得到一个错误。 So in your example the answer would be:所以在你的例子中,答案是:

this.$delete(this.users, 'foo')

or或者

vm.$delete(vm.users, 'foo')

https://v2.vuejs.org/v2/guide/migration.html#vm-delete-changed https://v2.vuejs.org/v2/guide/migration.html#vm-delete-changed

You have to create a new copy of the object so Vue be able to know that there are changes:您必须创建对象的新副本,以便 Vue 能够知道发生了变化:

ES6 ES6

const users = { ...this.users };
delete users['foo'];
this.users = users

or without spread operator it would be或者没有传播运算符

const users = Object.assign({}, this.users);
delete users['foo'];
this.users = users

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM