天天看點

mpvue:父元件向子元件傳值,子元件接收為空

在mpvue中,父元件在onLoad函數内擷取了資料,使用子元件時傳遞給了子元件,但總是報錯,發現子元件接收到的總是為undefined。接下來,我們先看看項目環境。我是在做我的收藏功能遇到這個問題的,在收藏頁面中使用了自定義元件。

mpvue:父元件向子元件傳值,子元件接收為空

運作的時候發現一直報錯,在子元件中将傳入值列印了出來發現一直是undefined。之後我在pages/colletion/index.vue 下列印了将created函數、onLoad函數、onShow函數列印了一下。

mpvue:父元件向子元件傳值,子元件接收為空

運作小程式:

mpvue:父元件向子元件傳值,子元件接收為空
mpvue:父元件向子元件傳值,子元件接收為空

在vue中我們習慣在created中準備資料,在渲染的時候,資料已經準備好了。但是在mpvue中,所有頁面的created函數是在小程式一開始的時候就被一次性執行。我們隻能在每個頁面的onLoad(),也就是頁面加載階段準備資料。這也造成了,有時候資料還沒準備好,就已經向子元件傳值了。解決方案有兩個,一個是使用子元件的時候使用v-if。另一個是使用$nextTick。下面貼出使用$nextTick方案的代碼:

<template>
  <div>
    <waterfall :dataList='collections'></waterfall>
  </div>
</template>

<script>
import waterfall from '../../components/waterfall'
export default {
  data () {
    return {
      collections: []
    }
  },
  methods: {
    initData () {
      console.log('調用了collection的初始化資料函數')
      this.$http.get({
        'url': '/collection/my_collections'
      }).then((res) => {
        console.log('collection中擷取資料完畢')
        this.$nextTick(() => {
          this.collections = res
        })
      })
    }
  },
  onLoad () {
    console.log('調用collection的onLoad')
    this.initData()
  },
  onShow () {
    console.log('調用了collection的onShow')
  },
  created () {
    console.log('調用collection的created')
  },
  components: {
    waterfall
  },
  //  下拉重新整理事件
  onPullDownRefresh () {
    this.collections = []
    this.initData()
  }
}
</script>

<style scoped   rel="stylesheet/stylus">
</style>