zoukankan      html  css  js  c++  java
  • Vue父组件传递异步获取的数据给子组件

    问题场景:

    当父组件传给子组件的数据是在父组件中异步获取的时候,如何让子组件获取期望的值?

    在父组件中:

    首先在data()中定义data_detail为空:

    data(){
      data_detail: {}      
    }

    然后将data_detail传递给子组件

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

    data_item是在父组件中异步请求的数据:

    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)
            }
          })
        },

    在子组件中:

    通过props接收父组件传递过来的值:

    props: ['data_item']

    当父组件的异步请求为loading状态的时候,data_item的值为空,此时子组件获取的也是空值,有时候需要用到data_item传递过来的值作为参数,这时就会获取不到data_item.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', '获取报告信息失败')
            }
          })  
        }

    解决方案:

    1.在父组件中加上v-if属性:

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

    2.在子组件中用watch监听数据变化后再调用函数

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

    如果上面两种方式都不能解决问题的话,那就用vuex来管理。

  • 相关阅读:
    设计模式:迭代器模式(Iterator Pattern) 明
    设计模式:目录导航 明
    设计模式:状态模式(State Pattern) 明
    设计模式:命令模式(Command Pattern) 明
    二维DP—— POJ 3186
    COM组件里自动化接口与普通接口的转换
    贪心好题——poj3044
    三分查找——POJ3301
    静态链表+DFS——poj 3272
    妙用队列优化——校赛题
  • 原文地址:https://www.cnblogs.com/angelatian/p/8932798.html
Copyright © 2011-2022 走看看