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>

 

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