Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
     }
  }
})
like image 244
silent_coder Avatar asked Jul 26 '17 23:07

silent_coder


1 Answers

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>
like image 111
Bert Avatar answered Oct 09 '22 11:10

Bert