Vue--关于子component使用props接收父component异步数据的注意点

在子component中使用props接收父component的数据,是在不包含vuex的项目中跨层级component数据传输的常规操作。
然而,这里并不总是一帆风顺的。在实际操作中,如果父component的某个属性对应的值并非静态定义的,而是通过异步接口获取的,子component直接用props引用,并在template中进行标签绑定,就很可能会出现问题。
现来看正常情况下的代码————

father component

    <template>
        <div id='father'>
            <p>This is father-component</p>
            <child-component :list="sublist"></child-component>
        </div>
    </template>
    <script>
        import child from './ChildComponent'
        export default {
            name: 'father',
            components: {
                child
            },
            data () {
                return {
                    sublist: [
                        {
                            title: "First",
                            imgurl: "http://.../first.jpg"
                        },
                        {
                            title: "Second",
                            imgurl: "http://.../second.jpg"
                        },
                        {
                            title: "Third",
                            imgurl: "http://.../third.jpg"
                        },
                    ]
                }
            },
            ...
        }
    </script>

child component

<template>
    <div id='child'>
        <ul>
            <li class='list-item' v-for="(item, index) in list" :key="`item-${index}`">{{ item.title }}
                <img :src="item.imgurl">
            </li>
        </ul>
    </div>
</template>
<script>
    export default {
        name: 'child',
        props: ['list'],
        ...
    }
</script>

以上代码中,childComponent通过fatherComponentsublist属性绑定到list的props上,并遍历其渲染<li>列表元素。此时我们的代码是能够正常运行的。
但是,很多情况下,尤其是在涉及到根组件初始化时的数据来源时,我们往往并不是使用硬编码好的数据进行存储,而是通过接口异步获取data,再给根组件的属性进行赋值。
还以上面的代码为主结构,假定我们全局已经引入了axios作为接口获取库,并进行了绑定 Vue.prototype.$http = axios,fatherComponent的代码修改如下————

    <script>
        import child from './ChildComponent'
        export default {
            name: 'father',
            components: {
                child
            },
            data () {
                return {
                    sublist: []
                }
            },
            mounted: {
               this.$http.get('http://.../..').then((resp) => {
                this.sublist = resp.data.sublist
               }).catch((err) => {
                console.log(`获取接口错误——${err}`)
               })
            },
            ...
        }
    </script>

此时,我们将fatherComponent的数据初始化为空Array,硬编码修改为了异步使用axios通过接口获取再赋值。如果childComponent的代码依旧不做任何改动,再运行,将会报错,报错内容如下

[Vue warn]: Error in render: "TypeError: Cannot read property 'title' of undefined"

并且在console的报错日志中,我们可以通过调用栈跟踪到,在<li>元素绑定props时报出了上述错误。
为什么呢?

事实上,在子元素渲染的时,就已经通过props去获取父组件传进来的数据了。然而此时,异步获取的数据尚未拿到并传入,但是子元素的mounted只会在最初执行一次,因此,渲染时所使用的props其实是一个空数组,所以绑定的每一个item都是undefined,当然无法获取到其title。**

通常,我们可以通过给childComponent增加一个watch观察器对propslist进行变化监控,但其实在常见情况下,该问题还有一个比较简便的解决方案————

给childComponent的渲染增加条件,v-if条件渲染。我们在fatherComponent中插入childComponent时可以写成如下形式

    <template>
        <div id='father'>
            <p>This is father-component</p>
            <child-component v-if="sublist.length" :list="sublist"></child-component>
        </div>
    </template>

通过v-if判断当前fathersublist是否含有内容,如果有内容,才对childComponent进行渲染,否则不渲染。
这样,只有当异步获取的数据填入sublist中之后,sublist.length不再为0,才会对childComponent进行渲染,childComponent中的list包含的item才能以对象的形式被取到title和imgurl属性的值

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 10,473评论 0 29
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,972评论 19 139
  • 组件(Component)是Vue.js最核心的功能,也是整个架构设计最精彩的地方,当然也是最难掌握的。...
    六个周阅读 10,942评论 0 32
  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 6,680评论 0 6
  • 感觉跟闯关一样,终于还有两个多月就能见到二宝了,尽管有年龄方面的原因,但还是坚信二宝所有的指标都是标准的。 做了四...
    我是可乐姐呢阅读 1,720评论 0 0

友情链接更多精彩内容