Sasha
Sasha

Reputation: 8705

Vue2 - update object same way as delete

Is there a way to update property the same way as Vue.delete is used?

I have this method:

let element = event.target
                    let url     = '/admin/services/changePriorityStatus/' + element.dataset.id

                    this.$dialog.confirm('Are you sure you want to change priority status of this service?',{
                        loader: true
                    }).then((dialog) => {

                        axios.post(url, {
                            id:       element.dataset.id,
                            priority: element.dataset.priority
                        })
                        .then((response) => {

                            let data = response.data
                            dialog.close()

                            let serviceIndex = this.services.findIndex(service => serviceID)

                            Vue.delete(this.services, serviceIndex);

                            Event.$emit('message:show', {
                                messageTitle: data.messageTitle,
                                messageText:  data.messageText
                            }, data.class)
                        })
                        .catch((error) => {

                            alert('Something went wrong. Please try again a bit later')
                            dialog.close()
                        })

                    })
                    .catch(() => {
                        console.log('Changing status canceled')
                    });

I want to replace Vue.delete with some global update method if it is possible. Is there a way to do this?

Upvotes: 0

Views: 105

Answers (1)

thibautg
thibautg

Reputation: 2042

Yes with Vue.set. However, it's only needed when adding a new property to an object, not when updating an already reactive property.

See https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats for more information:

Change Detection Caveats

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive.

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method.

Upvotes: 4

Related Questions