What to do when child props don't change even though parent data has changed in Vue
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents for Vue articles
I summarized what to try when child props don't change even though parent data has changed in Vue
Environment
Nuxt2.15.7
First of all
Vue generally automatically switches displays when data changes
The same applies when passing props from parent components to child components.
In general, the display will automatically change. That's the convenient part.
There are times when the display does not change automatically
Vue detects "data has changed" and switches only the display part accordingly.
So, when it can't detect "data has changed," the display part may not switch.
When can't it detect changes?
For example, it seems that it can't detect when part of a property in an associative array is rewritten.
this.posts[0].content = "Change Change Change"
If you rewrite it like this, the props of the child component may not be rewritten.
In other words, implement changes in a way that conveys the changes, or prompts for a reload
For example, with arrays, it seems that non-destructive change is necessary.
Changes will be conveyed with push or splice.
Things I want you to try
What you are about to do is,
this.posts[0].content = "Change Change Change"
Let's talk about how to convey this change to the child component.
Implement array changes using splice
data(){
return {
//Original data
posts: [
{id:1,content:'content1'},
{id:2,content:'content2'},
],
//Assume new data you want to change to is below
post: {
{id:1,content:'Change Change Change'}
}
}
},
methods: {
changeData: function(){
//Get the index of the array to be changed as post
const index = this.posts.findIndex((x) => x.id === post.id);
//Change the post at index 1 from index
this.posts.splice(index, 1, post);
}
}
Use $set to convey changes in object properties
this.$set(this.post, "content", "Change Change Change")
Reference
Vue Official "Reactivity Exploration"
It's mostly written here.
Summary
I introduced two things to try when child props don't change even though parent data has changed.
If you have complaints or corrections, please feel free to reach out to me via DM on Twitter below.
Thank you and goodbye!