Track property in vue component

I have an async operation on a parent component and need to notify child for this operation to complete. Can I supervise the child for the change of property. Likely:

new Vue({
   props:['parentReady'],
   watch:{
     parentReady(val){
       alert('parentReady prop was changed');
     }
  }
})

      

+3


source to share


1 answer


There are several ways to do this. You can set the property on the parent when the asynchronous activity has completed.



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>
      

Run code


You can call the 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>
      

Run code


You can just look at 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>
      

Run code


+2


source







All Articles