Reputation: 105
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.
Upvotes: 0
Views: 4036
Reputation: 63059
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>
Upvotes: 3
Reputation: 1544
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.
Upvotes: 1
Reputation: 16513
Just do:
this.object.three = { } // just make it empty, or
delete this.object.three // or
delete this.object['three']
Upvotes: -1