vue父組件異步獲取動(dòng)態(tài)數(shù)據(jù)傳遞給子組件 獲取不到值的問題已完美解決 附demo

前幾天遇到一個(gè)問題,在父組件中使用axios獲取異步數(shù)據(jù)傳給子組件,但是發(fā)現(xiàn)子組件在渲染的時(shí)候并沒有數(shù)據(jù),在created里面打印也是空的,結(jié)果發(fā)現(xiàn)一開始子組件綁定的數(shù)據(jù)是空的,在請求數(shù)據(jù)沒有返回?cái)?shù)據(jù)時(shí),子組件就已經(jīng)加載了,并且他綁定的值也是空的,問題找到了,怎么解決那?有兩種方法解決,請看下面代碼。

方法一、

開始的時(shí)候讓子組件隱藏,然后等數(shù)據(jù)返回的時(shí)候,讓子組件顯示。
<template>
  <div class="list">
    <ul v-if="list.length != 0">
      <li v-for="(item,index) in list" :key="index"</li>
    </ul>
  </div>
</template>
<script>
export default {
  props:['getList'], //接收一個(gè)數(shù)組
    data(){
      return {
        list: []
      }
    },
    watch:{   // 使用監(jiān)聽的方式,監(jiān)聽數(shù)據(jù)的變化
      getList(val){
        this.list = val;
      }
    }
}
</script>
不過這樣方式不太合適,有bug,比如我點(diǎn)擊一個(gè)按鈕去獲取數(shù)據(jù),然后在彈框里面展示數(shù)據(jù),彈框是一個(gè)子組件,在獲取數(shù)據(jù)的這段過程有可能幾百毫秒,也有可能十秒或者更長時(shí)間,難道我要在點(diǎn)擊按鈕過十秒才讓彈框顯示嗎?這這這絕對不行,推薦使用方法二

方法二、 推薦使用

大概邏輯:使用vuex全局狀態(tài)管理,其實(shí)簡單,利用vuex的輔助函數(shù)(mapState,mapMutations)mapState是將state里面的數(shù)據(jù)映射到計(jì)算中(computed),mapMutations也是類似,把vuex中mutations的方法映射到組件里面,就可以在組件里面直接使用方法了,在vuex中使用異步(actions)去掉用接口,然后在接口成功的函數(shù)里面取觸發(fā)同步(mutations)里面的方法,把得到數(shù)據(jù)傳給mutations里面的方法里并且給state里面的屬性賦值,然后就可以在子組件中使用computed計(jì)算中去獲取數(shù)據(jù)并且渲染到頁面上,其實(shí)說的有點(diǎn)繞( -_-"),但是看代碼就明白了 。
vuex / index.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex) 
export default new Vuex.Store({  
    //定義初始數(shù)據(jù)
    state: {  
        title: '',
        list: [],
        isShow: false
    },
    //同步的方法
    mutations: {
        //向state 里面設(shè)置數(shù)據(jù)
        changeListMutation(state, list) {
            state.list = list
        },
        //在list.vue里面點(diǎn)擊下拉選項(xiàng)的時(shí)候觸發(fā) 給state.title賦值
        changeTitleMutation(state, title) {
            state.title = title
        },
        //selectinput.vue里面點(diǎn)擊input的時(shí)候觸發(fā) 給state.isShow賦值
        toggleShow(state, isShow) {
            state.isShow = isShow 
        }
    },
    //異步的方法
    actions: {
        //在list.vue里面created生命周期里面觸發(fā)
        getListAction({ commit }) {
            axios.get('/mock/5afd9dc0c088691e06a6ab45/example/dataList')
                .then((res) => {
                    commit('changeListMutation', res.data) //調(diào)用mutations下面的changeListMutation方法并且傳值過去
                })
                .catch((error) => {
                    console.log(error)
                })

        }
    }
})
// 觸發(fā)異步里面的方法是用 this.$store.dispatch('這里是方法名')
// 觸發(fā)同步里面的方法是用 this.$store.commit('這里是方法名')
父組件 select.vue
這個(gè)頁面只是引入兩個(gè)子組件,沒有什么好說的
<template>
  <div class="select">
    <div class="wrap">
        <selectInput></selectInput>
        <list></list>
    </div>
  </div>
</template>
<script>
  // 引入子組件 
  import selectInput from '@/components/selectInput'  
  import list from '@/components/list'
  export default {
    components:{   //加載子組件
      selectInput,
      list
    },
  }
</script>
<style>
  .select{
    background:#4a56fe;
    width: 400px;
    margin: 100px auto 0;
    padding: 40px;
    border-radius: 10px;
  }
  .wrap{
    background: #e3e5fe;
    border-radius: 10px;
    padding: 40px;
  }
  ul{
    list-style: none;
  }
</style>
子組件 list.vue
該組件就是展示下拉選項(xiàng),并且調(diào)用數(shù)據(jù)渲染
<template>
  <div class="list">
    <ul>
      <li v-for="(item,index) in list" :key="index" v-show="initShow" @click="changeTitle(item.title)">{{item.title}}</li>
    </ul>
  </div>
</template>

<script>
    import {mapState,mapMutations} from 'vuex'  // 將vuex中的state數(shù)據(jù)和mutations中的方法映射到組件中
    export default {
        //vue 生命周期(created)在實(shí)例創(chuàng)建之后,在數(shù)據(jù)初始化之前被調(diào)用
        created(){  
            this.$store.dispatch('getListAction')  //調(diào)用vuex 中的 getListAction異步方法
        },
        //計(jì)算state數(shù)據(jù)
        computed:{
            ...mapState({
              list:'list',
              initShow:'isShow'
            })
        },
        methods:{
            changeTitle(title){
              this.$store.commit('changeTitleMutation',title)
              this.$store.commit('toggleShow',!this.initShow)
            }
        }
    }
</script>
// 觸發(fā)異步里面的方法是用 this.$store.dispatch('這里是方法名')
// 觸發(fā)同步里面的方法是用 this.$store.commit('這里是方法名')

<style>
  .list{
    padding: 10px 0;
    text-align: center;
  }
  li{
    line-height: 30px;
    height: 30px;
    border-radius: 15px;
    cursor: pointer;
    color:#535353;
  }
  li:hover{
    background: #ff705b;
    color: #fff;
  }
</style>
子組件 selectinput.vue
該組件展示選中的數(shù)據(jù)
<template>
  <div class="inputBox">
    <input type="text" readonly :value="getTitle" @click="toggleShow" placeholder="你喜歡什么">
  </div>
</template>

<script>
export default {
  computed:{
    // 獲取vuex中的state數(shù)據(jù)并賦值綁定到 value上面  computed 里面的方法名其實(shí)就是相當(dāng)于 data里面的數(shù)據(jù),可以用this.getTitle 去訪問
    getTitle(){ 
      return this.$store.state.title
    },
    // 初始化控制下拉選項(xiàng)顯示隱藏的狀態(tài),如果isShow是false 則不限是下拉菜單,默認(rèn)是false
    initShow(){
        return this.$store.state.isShow
    }
  },
  methods:{
    //點(diǎn)擊input的時(shí)候調(diào)用該方法,這個(gè)方法去觸發(fā)mutations下面的toggleShow,去改變isShow的狀態(tài),默認(rèn)是isShow等于false, 然后在點(diǎn)擊的時(shí)候去改變isShow 等于true ,  !this.initShow就是true,如果是true的話,下拉選項(xiàng)才能出來,并將改變過后的值傳給toggleShow方法,去給vuex/store.js 里面的state.isShow賦值。
    toggleShow(){
      this.$store.commit('toggleShow',!this.initShow)
    }
  }
}
</script>

<style>
input{
  outline: none;
  width: 100%;
  height: 40px;
  line-height: 40px;
  border-radius: 10px;
  border: 1px solid #d3d3d3;
  text-indent: 20px;
  color: #535353;
}
</style>

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • ## 框架和庫的區(qū)別?> 框架(framework):一套完整的軟件設(shè)計(jì)架構(gòu)和**解決方案**。> > 庫(lib...
    Rui_bdad閱讀 2,973評論 1 4
  • vue概述 在官方文檔中,有一句話對Vue的定位說的很明確:Vue.js 的核心是一個(gè)允許采用簡潔的模板語法來聲明...
    li4065閱讀 7,275評論 0 25
  • vuex 場景重現(xiàn):一個(gè)用戶在注冊頁面注冊了手機(jī)號碼,跳轉(zhuǎn)到登錄頁面也想拿到這個(gè)手機(jī)號碼,你可以通過vue的組件化...
    sunny519111閱讀 8,035評論 4 111
  • 理解vue 引用一段官方的原話: Vue.js(讀音 /vju?/,類似于 view) 是一套構(gòu)建用戶界面的漸進(jìn)式...
    綽號陸拾柒閱讀 2,399評論 3 6
  • 有一句話叫做:好的愛情是你通過一個(gè)人看到整個(gè)世界,而壞的愛情是你為了一個(gè)人舍棄世界。 好久之前我以為只是一句“嗯,...
    東城LEO閱讀 445評論 0 1