Home > front end >  Triggering Vue.js reactivity when adding a new key to an object
Triggering Vue.js reactivity when adding a new key to an object

Time:05-15

I am using the following function to add a new key/value pair to an object.

                .then(response => {
                    this.plantRegisteredMaterials = response.data.tenantPlantMaterials.edges;
                    this.plantRegisteredMaterials.forEach(plantMaterial => {
                        this.materials.forEach(tenantMaterial => {
                            if (
                                tenantMaterial.node.id ==
                                plantMaterial.node.material.id
                            ) {
                                tenantMaterial.node.isRegistered = true; //This is the new key I want Vue to recognize
                            } else tenantMaterial.node.isRegistered = false; //This is the new key I want Vue to recognize
                        });
                    });
                });

This object is used as items on a v-data-table.

However when I add this new key/value pair to the object, Vue doesn't recognize it and those changes are not detected by the v-data-table unless I click on something like Sort or anything else that forces the DOM to re-render.

I know there is some way to force Vue to recognize those changes. How Should I do it ?

I tried JSON.parse and JSON.stringify() as I have read in some other topics , but it doesnt seem to work.

CodePudding user response:

Vue cannot detect adding a new key to an Object. (source)

You have two options:

1: Add the new key using this.$set(tenantMaterial.node, 'isRegistered', true)

2: Fully construct a plain Javascript object before assigning it to the reactive Vue object:

const plantRegisteredMaterials = response.data.tenantPlantMaterials.edges

plantRegisteredMaterials.forEach(plantMaterial => {
  // Add, remove, change keys of plantMaterial
  ...
})
this.plantRegisteredMaterials = plantRegisteredMaterials
  • Related