I have an async operation in parent component and need to notify child, that this operation was completed. Could I watch in child for a property change. Somewhat like:
new Vue({
props:['parentReady'],
watch:{
parentReady(val){
alert('parentReady prop was changed');
}
}
})
There are several ways you could do this. You could set a property in the parent when the asynchronous action was complete.
console.clear()
Vue.component("child", {
props: ["parentLoading"],
template: `
<h1 v-if="isParentLoading">Parent is loading...</h1>
<h1 v-else>Parent loading complete!</h1>
`,
computed: {
isParentLoading() {
return this.parentLoading
}
}
})
new Vue({
el: "#app",
data: {
loading: true
},
mounted() {
setTimeout(() => this.loading = false, 2000)
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<child :parent-loading="loading"></child>
</div>
You could call a method on the child.
console.clear()
Vue.component("child",{
template:`
<h1 v-if="!loaded">Parent is loading...</h1>
<h1 v-else>Parent loading complete!</h1>
`,
data(){
return {
loaded: false
}
},
methods:{
onLoaded(){
this.loaded = true
}
}
})
new Vue({
el:"#app",
mounted(){
setTimeout(() => this.$refs.child.onLoaded(), 2000)
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<child ref="child"></child>
</div>
You could just watch the property.
console.clear()
Vue.component("child", {
props: ["parentLoading"],
template: `
<h1 v-if="parentLoading">Parent is loading...</h1>
<h1 v-else>Parent loading complete!</h1>
`,
watch: {
parentLoading(newVal) {
return newVal
}
}
})
new Vue({
el: "#app",
data: {
loading: true
},
mounted() {
setTimeout(() => this.loading = false, 2000)
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<child :parent-loading="loading"></child>
</div>
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