Js 2: 从数据对象中删除属性

如何从 Vue.js 数据对象(即关联数组)中删除属性/密钥,如下所示:

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

我在谷歌上搜索了一下,找到了两种方法,但都不管用:

  • delete this.users.foo;没有更新 DOM
  • this.users.splice('foo', 1);根本无法工作(可能只能在数组上工作,而不能在对象上工作)
73534 次浏览

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

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. 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

You have to create a new copy of the object so Vue be able to know that there are changes:

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