vue.js未定義 - 已經獲取到資料並渲染在頁面上,但是警告未定義
[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
思考了一下原因,是不是因為頁面進行了渲染和請求介面獲取資料,非同步進行,所以獲取資料沒有完成時,頁面已經進行渲染,所以第一次報使用未定義變數,等資料獲取到之後,再次渲染,所以頁面內容顯示出來了,第一次的警告也產生了~