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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44954459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:48:38  来源:igfitidea点击:

Vue.js 2: Delete property from data object

javascriptvue.jsvuejs2

提问by Thomas Landauer

How can you delete a property/key from a Vue.js data object (i.e. 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
  • this.users.splice('foo', 1);is not working at all (probably only works on arrays, not on objects)
  • delete this.users.foo;不更新 DOM
  • this.users.splice('foo', 1);根本不起作用(可能只适用于数组,不适用于对象)

回答by Thomas Landauer

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

回答by Sadraque Santos

It's important to know that vm.$deleteis a alias for Vue.deleteand if you try something like this.delete()you will get a error. So in your example the answer would be:

重要的是要知道这vm.$delete是一个别名Vue.delete,如果你尝试类似的东西,this.delete()你会得到一个错误。所以在你的例子中,答案是:

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

or

或者

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

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

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

回答by Maksim Bazarov

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 operatorit would be

或者没有传播运算符,它将是

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