I know this has been asked a lot here in different forms, but I'm having trouble getting a child to be reactive to changes made in the parent. I have tried key changing, but that doesn't seem to work in this case.
Shouldn't a child component know to re-render itself when a prop it is receiving has changed?
For example (this is not my exact component, just an example of the data flow):
<template>
<div id="parent">
<h1>Sort By</h1>
<button @click"handleClick('alpha')">Alphabetical</button>
<button @click"handleClick('price')">Price</button>
<ChildComponent :sortBy="sortBy" :key="keyChangingDoesntWork" /> // doesn't update when 'sortBy' changes.
</div>
</template>
<script>
// ...
name: "parent",
data(){
return{
sortBy: 'alpha',
}
},
methods: {
handleClick(by){
if (by === 'alpha') {
this.sortBy = 'alpha'
} else {
this.sortBy = 'price'
}
}
}
</script>
// child
<script>
props: {
sortBy: String
}
updated() {
console.log(this.sortBy); // need this to change when buttons are clicked in parent
}
</script>
You can watch props as below
Parent:
<template>
<div id="parent">
<h1>Sort By</h1>
<button @click="handleClick('alpha')">Alphabetical</button>
<button @click="handleClick('price')">Price</button>
<ChildComponent v-bind:sortBy="sortBy" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent';
export default {
name: "parent",
data() {
return {
sortBy: 'alpha',
keyChangingDoesntWork: 1
}
},
components: {
'ChildComponent': ChildComponent
},
methods: {
handleClick(by) {
if (by === 'alpha') {
this.sortBy = 'alpha'
} else {
this.sortBy = 'price'
}
return this.sortBy;
}
},
}
</script>
Child:
<template>
<div>
<h5>Child: {{ sortBy }}</h5>
</div>
<!-- prop change watch-->
</template>
<script>
export default {
props: {
sortBy: String,
},
watch: {
sortBy: function (newVal, oldVal) {
// watch it
console.log("Prop changed: ", newVal, " | was: ", oldVal);
},
},
};
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With