silent_coder silent_coder - 1 year ago 408
Javascript Question

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

Answer Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download