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.
>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);
});
}
}