-1

I have been troubled by a question for a long time. Now I am using Vue.js to develop a web project. What I want to do is to pass data from parent to child component. However, the child component's main program would run only after the props data was received, due to the async data transmission mechanism. So I would like to know whether these are some ways to check the status of props data in the child component. Therefore I can make sure the subsequent task would run after the data was passed.

For example, a feasible solution is axios.requset({..}).then(res => {..}).

1 Answers1

0

You can use the watchers in your child component. Consider the following parent component:

Vue.component('parent-comp', {
  
  props: ['myProp'],
  template: `
    <div>
      <child-comp my-prop={someAsyncProp} />
    </div>
  `,

  data() {
    return {
      // Declare async value
      someAsyncProp: null
    };
  },

  mounted() {
    // Some async computation
    axios
      .requset({ url: '/get-data' })
      .then(res => {
        // Set value asynchronously
        this.someAsyncProp = res;
      });
  }
});

Your child component would use watchers to check if data is available:

Vue.component('child-comp', {
  
  props: ['myProp'],
  template: '<div></div>',

  watch: {
    // Watch the property myProp
    myProp(newValue, oldValue) {

      if (newValue !== null) {
        // Do something with the props that are set asynchronously by parent
      }

    }
  }
})
Harshal Patil
  • 17,838
  • 14
  • 60
  • 126