uni-app页面向组件传值(传的是对象)报错问题
问题描述
在页面中通过异步请求
获取了信息详情数据
,这个详情数据需要传给导入的组件,在组件中进行使用,这个时候有报错,报错内容为Error in render: "TypeError: Cannot read property '1' of undefined"
解决方案
(1)在使用组件的页面data
中添加一个变量flag
,初始值为false
,因为数据是异步请求过来的,因此在给list
赋值后,将flag
置为true
;
(2)在页面使用组件的时候,加上v-if="flag"
。
3、代码复现
- 使用组件的页面:传的值为list中的item对象
<template>
<uni-swipe-action>
<uni-swipe-action-item
v-for="(item, index) in list"
:key="item.id"
:right-options="options"
@click="bindClick(item.id, index)"
@change="swipeChange(item.id, index)"
>
<listItem v-if="flag" :detailInfo="item"></listItem>
</uni-swipe-action-item>
</uni-swipe-action>
</template>
<script>
import listItem from '@/components/common/list-item.vue';
import { getInfo } from '@/utils/api.js';
export default {
components: {
listItem
},
data() {
return {
flag: false, // 初始的flag
list: []
}
},
onLoad() {
this.getData();
},
methods: {
async getData() {
var res = await getInfo();
if (res.data.code !== 200) {
uni.showToast(res.data.desc)
return
}
this.list = res.data.data;
// 表示可以开始渲染组建了,flag置为true
this.flag = true;
}
}
</script>
- 组件
<template>
<view class="card">
<view class="title">{{detailInfo.title}}</view>
<view class="desc">{{detailInfo.desc}}</view>
</view>
</template>
<script>
export default {
props: {
detailInfo: {
type: Object,
required: true
}
},
data() {
return {}
},
mounted() { },
methods: {
}
}
问题原理
(1)准备工作:子组件与父组件的生命周期执行顺序
父beforeCreate
—— 父created
—— 父beforeMount
—— 子beforeCreate
—— 子created
—— 子beforeMount
—— 子mounted
——父mounted
——父beforeUpdate
——子beforeUpdate
——子updated
——父updated
——父beforeDestroy
——子beforeDestroy
——子destroyed
——父destroyed
(2)从上面的父子组件生命周期执行顺序可以得知(子组件的mounted
在父组件的mounted
之前执行),在使用子组件时,子组件的结构是有可能比父组件的结构渲染得早,再加上父组件传给子组件的值要是异步请求
得来的,这样就会导致父组件的值在子组件渲染完成后才传过去的,因此,会出现property ‘XXX’ of undefined
。
解决方案中,正好是在异步数据回来之后,再去渲染子组件,这样就不会出现子组件渲染太快导致最开始没有纸的情况。