Categories
Vue Answers

How to Delete a Property from Data Object with Vue.js?

Spread the love

Sometimes, we want to delete a property from a data object with Vue.js.

In this article, we’ll look at how to delete a property from a data object with Vue.js.

Delete a Property from Data Object with Vue.js

To delete a property from a data object with Vue.js, we can use the this.$delete method.

For instance, we can write:

<template>
  <div id="app">
    {{ users }}
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      users: {
        foo: { firstName: "jane", lastName: "smith" },
        bar: { firstName: "john", lastName: "green" },
      },
    };
  },
  mounted() {
    this.$delete(this.users, "foo");
  },
};
</script>

to delete the foo property from the this.users reactive property with the this.$delete method.

The $delete method will trigger Vue’s reactivity to update the this.users object to remove the foo property.

So from the template, we should see that users is now:

{ "bar": { "firstName": "john", "lastName": "green" } }

We can also use the Vue.delete method to do the same thing by writing:

<template>
  <div id="app">
    {{ users }}
  </div>
</template>

<script>
import Vue from "vue";

export default {
  name: "App",
  data() {
    return {
      users: {
        foo: { firstName: "jane", lastName: "smith" },
        bar: { firstName: "john", lastName: "green" },
      },
    };
  },
  mounted() {
    Vue.delete(this.users, "foo");
  },
};
</script>

We just replace this.$delete with Vue.delete .

Conclusion

To delete a property from a data object with Vue.js, we can use the this.$delete method.

We can also use the Vue.delete method to do the same thing.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *