说一下为什么会有这个需求:如果不需要处理props的值直接用,是不用这么麻烦的,
直接在页面上用{{name}}就好了。在做项目的时候由于要对props的值做处理后才能使用,当我在methods、mounted 用this.xxx,发现取出来的值是空对象,有点疑惑
于是就上网查了原来:
通过这个方法传过来的值,在子组件mounted函数中如果直接去获取的话有可能会获取不到。因为此时父组件的值还没有传过来,但是如果你是写在methods中的方法中获取值的话,此时值已经传过来了,可以直接使用this.name获取到。 如果你想要在子组件的mounted()中获取传值的话最好做个延迟或者是监听,但是又有一点,为啥我在页面中使用{{name}}没有问题呢! 这就是vue的好处它是等到这个name值有变化的时候就会更新的。所以才会看到显示。(其实先是空然后值传过来了,就会加载上去。)

https://segmentfault.com/q/1010000014590428 (原文链接)

解决方法,直接上代码了:

父组件代码:

<template>
	// 将photoList 传给子组件
  <div class="home"><photo-view :photoList="photoList"></photo-view></div>
</template>
<script>
import PhotoView from './components/PhotoView'
import axios from 'axios'

export default {
  name: 'Home',
  components: {
    PhotoView
  },
  data () {
    return {
      photoList: []
    }
  },
  mounted () {
    this.getPhotoInfo()
    this.getPushText()
  },
  methods: {  
    getPhotoInfo () {
    // 获取后台数据通过getPhotoInfoSucc得到photoList 
      axios.get('./mock/photo.json')
        .then(this.getPhotoInfoSucc)
    },
    getPhotoInfoSucc (res) {
      res = res.data
      if (res.data) {
        const data = res.data
        this.photoList = data
        console.log(data)
      }
    }
  }
}
</script>

子组件代码:

<template>
</template>
<script>
export default {
  name: 'PhotoView',
  props: {
    photoList: Array
  },
  data () {
    return {
      newPhotoList: [],
    }
  },
  //监听photoList的值,当它由空转变时就会触发,这时候就能取到了,拿到值后要传值到data的newPhotoList中
  watch: {
    photoList: function (newData) {
      this.newPhotoList = newData
      this.getPhotoList(this.newPhotoList)
    }
  },
  methods: {
    getPhotoList (res) {  
    console.log(this.newPhotoList)
  }
}
</script>

这里是参考https://www.jianshu.com/p/cdc90de5b1cf

个人学习笔记,如有误,请指教,谢谢

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐