Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vuejs: update props from children component but props does not change instantly?

I’m trying to update an prop value from a child component using this.$emit(‘updateData’, data); when i log the data received in parent component, it did changed. But when i logged it out in my child component it didn’t change. Here is my code:

<child :propDataFromParent="someData"></child>

props: ['propDataFromParent']
methods: {
   updateData(data) {
      this.$emit('updateData', data);
      console.log(this.propDataFromParent);
   }
}

I tried google search, and use chatgpt but it not helping.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In Vue, this.$emit is asynchronous. If you immediately print the updated value after calling this.$emit, you may not see the updated value.

The reason is that in Vue, the parent component listens to events emitted by the child component to receive data. When you call this.$emit(‘updateData’, data), Vue will trigger the event handler in the parent component after the current code block has finished executing.

If you want to print the updated value in the console.log, you can use the $nextTick method provided by Vue. It executes a callback function after the DOM has been updated. This ensures that the value is printed after the update is complete.

Here is the modified code example:

methods: {
  updateData(data) {
    this.$emit('updateData', data);

    this.$nextTick(() => {
      console.log(this.propDataFromParent);
    });
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading