Vue parent component passes asynchronously obtained data to child components

Problem scenario:

When the data passed from the parent component to the child component is obtained asynchronously in the parent component, how can the child component get the expected value?

In parent component:

First define data_detail as empty in data():

data(){
  data_detail: {}      
}

then pass the data_detail to the child component

<enterpriseDetail :data_item='data_detail'></enterpriseDetail>

data_item is the data requested asynchronously in the parent component:

searchDataDetail(){
      var self = this;
      self.data_detail_loading = true
      var param = {}
      param.data_id = self.search_history[0].data_id
      param.data_type = self.search_history[0].data_type
      param.search_name = self.search_history[0].search_name

      self.api.searchDataDetail(param).then(function(res) {

        if(res.errcode == 0){
          self.data_detail = res.data
          self.data_detail_loading = false
        }else{
          self.$store.commit('newMsg',res.errmsg)
        }
      })
    },

In child component:

Receive the value passed by the parent component through props:

props: ['data_item']

When the asynchronous request of the parent component is in the loading state, the value of data_item is empty, and the child component obtains an empty value. Sometimes the value passed by data_item needs to be used as a parameter, and then data_item cannot be obtained. The parameter enterprise_name

mounted() {this.checkDataexist()
}
   checkDataexist(){
      let that = this
      let param = {
        data_type: "enterprisecreditreport",
        data_info: that.data_item.enterprise_name
      }

      axios.post('/data/checkdataexists', param).then((res) => {
        if(res.data.errcode === 0){
          that.report_data = res.data.data
        }else{
          that.$store.commit( 'newMsg', 'Failed to get report information' )
        }
      })  
    }

solution:

1. Add the v-if attribute to the parent component:

<enterpriseDetail v-if='data_detail.enterprsie_name' :data_item='data_detail'></enterpriseDetail>

2. Use watch to monitor data changes in the child component and then call the function

watch: {
    data_item(val,newVal){
      this.$nextTick(() => {
        this.checkDataexist()
      })
   }},

If the above two methods can not solve the problem, then use vuex to manage.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324875240&siteId=291194637