Home > Blockchain >  Modifying variable in method does not update child component
Modifying variable in method does not update child component

Time:10-01

I'm struggling with how Vue updates props/child components.

Suppose the following component:

<template>
  <v-card>
    <Modification v-model="newObjekt"></Modification>
    <OtherComponent @close="resetObject"></OtherComponent>
  </v-card>
</template>

<script>
import { MyClass } from "classes";
import Modification from "b";
import OtherComponent from "a";

export default {
  name: "ShiftForm",
  components: { OtherComponent, Modification },
  props: {
    existingObject: {
      type: [MyClass, typeof undefined],
      required: false,
      default: undefined
    }
  },
  data() {
    return {
      newObject: undefined
    };
  },
  created() {
    this.newObject =
      this.existingObject !== undefined
        ? this.existingObject.clone()
        : new MyClass();
  },
  methods: {
    resetObject() {
      this.newObject =
        this.existingObject !== undefined
          ? this.existingObject.clone()
          : new MyClass();
    }
  }
};
</script>

This component receives an existing class instance of MyClass, clones it (clone => new MyClass(...)) and passes it to the Modification component which does some modification upon user input. So far so good, the modification works. However once the customEvent is fired and the resetObject method is called the newObject is reset but the Modification component is not updated with the now reset newObject - it still displays the old, modified values. I also checked inside the Modification component wether or not the update happens: It doesn't.

Why is this the case? Am I missing a step? Am I not aware of a Vue specific mechanism?

Note: I found this blog which provides solutions to force the Modificationcomponent to update. For now it seems to hacky for me to be "THE" solution.

Thanks in advance.

CodePudding user response:

You didn't show how MyClass clones your object.

I'm guessing something in there isn't reactive.

You can check by doing console.log() and see what it says on the console.

If it's reactive, it should show something like MyClass {__ob__: Observer}

You can probably use this.$set('propName', value) to fix your problem

Docs: https://v2.vuejs.org/v2/api/#vm-set

Adds a property to a reactive object, ensuring the new property is also reactive, so triggers view updates. This must be used to add new properties to reactive objects, as Vue cannot detect normal property additions (e.g. this.myObject.newProperty = 'hi').

CodePudding user response:

Either there is a typo in your post, or the typo also exists in your code and is the source of your problem.

In your post you're binding "newObjekt" to the Modification component, but your parent component has the property "newObject"

is this the source of your issue?

  • Related