注意vue组件中的属性

sil*_*der 7 javascript vue.js vuejs2

我在父组件中有一个异步操作,需要通知子,这个操作已经完成.我可以在孩子看房产改变吗?有点像:

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

Ber*_*ert 7

有几种方法可以做到这一点.您可以在异步操作完成时在父级中设置属性.

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)
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <child :parent-loading="loading"></child>
</div>
Run Code Online (Sandbox Code Playgroud)

你可以在孩子身上调用一个方法.

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)
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <child ref="child"></child>
</div>
Run Code Online (Sandbox Code Playgroud)

你可以看看这个房产.

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)
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <child :parent-loading="loading"></child>
</div>
Run Code Online (Sandbox Code Playgroud)