0

I have this object:

this.object = {
  one: { ... },
  two: { ... },
  three: { ... }
}

How can I remove, for example, the property three and make the UI rerender? I already tried to use delete but it seems that it does not change the state and the UI did not rerender.

When I use this.object = { }, it does rerender the UI. Last question, what type of object is this? Because it's hard to find an example or answer that uses this type of object.

3 Answers 3

3

From the Vue Reactivity Guide (which doesn't specifically tell you how to delete)

Vue cannot detect property addition or deletion

In order for these mutations to be reactive, you have to use Vue's built-in methods. You could do:

this.$delete(this.object, 'three');

OR

this.$set(this.object, 'three', undefined);

To answer your question about the object, it's an object literal.

Demo:

Vue.config.productionTip = false;
Vue.config.devtools = false
new Vue({
  el: "#app",
  data() {
    return {
      object: {
        one: {},
        two: {},
        three: {}
      }
    }
  },
  methods: {
    deleteProp() {
      this.$delete(this.object, 'three');
      //this.$set(this.object, 'three', undefined);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ object }}
  <button @click="deleteProp">Delete property</button>
</div>

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

Comments

1

Try this in the component

<template>
    <ul>
        <li v-for="(obj,key) in object" @click="deleteKey(key)">{{obj}}</li>
    </ul>
</template>

export default {
    name: "YourComponent",
    data: () => {
        return {
            object: {
                one: {},
                two: {},
                three: {}
            }
        }
    },
    methods: {
        deleteKey: function (key) {
            this.$delete(this.object, key);
        }
    },
    components: {Loader}
}

On clicking the listed values, it will be removed and can see the UI changing.

Comments

-1

Just do:

this.object.three = { } // just make it empty, or
delete this.object.three // or
delete this.object['three']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.