简体   繁体   中英

watch for a property in vue component

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/vue@2.2.6/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/vue@2.2.6/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/vue@2.2.6/dist/vue.js"></script> <div id="app"> <child :parent-loading="loading"></child> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM