[Vue warn]: Error in render: "TypeError: Cannot read property 'avatar' of undefined"
TypeError: Cannot read property 'avatar' of undefined
上面警告的内容,文章的结尾是处理的办法~可以跳过中间部分
以上是报错,avatar是后台获取到的数组对象中的一个key,数据可以获取到,但是提示了一个未定义的警告
不完整代码,只是为了显示错误,整个过程是,在父组件中调用接口,获取content对象数组,将对象数组传给三个子组件
子组件直接接收父组件传递过来的数组,使用数组中对象的key为avatar的值
父组件 :在父组件中调用接口,获取到content列表,将整个列表数据传给子组件
<keep-alive>
<component v-bind:is="titleBoxActiveView" :content="content"></component>
</keep-alive>
<script>
import title1 from './knowAboutUs/introductionTitle' //公司介绍 - 标题
import title2 from './knowAboutUs/valueTitle' //未来价值 - 标题
import title3 from './knowAboutUs/teamTitle' //管理团队 - 标题
export default{
name:'knowAboutUs',
data(){
return{
contentActive:false,
titleBoxActiveView:'title1', //标题默认加载第一个
activeIndex:1, //默认激活第一个
title:'了解我们',
pageindex:0,
content:[], //获取的内容 - 图片内容标题等
}
},
components:{
title1,
title2
title3,
},
methods:{
tabContentTitle(index){
this.titleBoxActiveView = 'title' + index ;
},
getContent(){ //获取内容
this.$store.dispatch('knowAboutUs/getContent').then(() => {
if(this.$store.state.knowAboutUs.code == 200){
this.content = this.$store.state.knowAboutUs.list;
}else{
this.$toast({message:this.$store.state.knowAboutUs.msg,});
}
}).catch((e) => {
alert(输入错误);
})
}
}
}
</script>
子组件:第一个子组件,默认在父组件加载的
// 关于我们 - 公司介绍标题部分
<template>
<div id="introductionTitle">
<img :src="content.length && content[0].avatar" alt="intro">
</div>
</template>
<script>
export default{
props:['content']
}
</script>
<style scoped>
img{width:100%;height:100%;}
</style>
子组件2:第二个子组件
// 关于我们 - 未来价值标题部分
<template>
<div id="valueTitle">
<img :src="content[1].avatar" alt="valueTitle">
</div>
</template>
<script>
export default{
props:['content']
}
</script>
<style scoped>
img{ width:100%; height:100% }
</style>
问题:
子组件2,可以直接使用父组件传过来的content数组,获取其中的avatar,不报未定义,但是第一个默认加载的组件
使用content[0].avatar时,提示下面的错误,但是数据可以获取到,也可以加载到页面上,只是使用时显示没有定义~
[Vue warn]: Error in render: "TypeError: Cannot read property 'avatar' of undefined"
TypeError: Cannot read property 'avatar' of undefined
解决:
*****将 contetn[0].avatar 换成 content.length && content[0].avatar
思考了一下原因,是不是因为页面进行了渲染和请求接口获取数据,异步进行,所以获取数据没有完成时,页面已经进行渲染,所以第一次报使用未定义变量,等数据获取到之后,再次渲染,所以页面内容显示出来了,第一次的警告也产生了~