mpvue:父組件向子組件傳值,子組件接收爲空

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

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

運行小程序:

 

在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  lang="stylus" rel="stylesheet/stylus">
</style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章