95

How can you delete a property/key from a Vue.js data object (i.e. associative array) like this:

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)
1
  • I believe vue2 implements its own splice for array. Wouldn't work on objects though, as you say. Commented May 1, 2019 at 1:41

3 Answers 3

187

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

Sign up to request clarification or add additional context in comments.

3 Comments

Weirdly, it's not even described in the documentation: vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats. It just says "Vue cannot detect property addition or deletion" and doesn't explain how you're supposed to do it
@Migwell it seems to be mentioned here: vuejs.org/2016/02/06/common-gotchas
It's worth noting that if you want to add a property to an object, the analogue is Vue.set.
108

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

1 Comment

Thank you very much.It's acutally a correct answer. It can solve the VUEJS problem which cannot watch data removed from or added to.
4

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

1 Comment

using Vue.delete is preferable to this solution since it doesn't involve creating a whole new object as it is done here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.