問題復現
使用vue-cli 框架對組件進行賦值時報錯:Cannot read property 'name' of undefined"
代碼:
<template>
<el-row :gutter="0">
<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
<img class="head-img" src="../assets/img/default.png" alt="頭像" />
<h3 class="user-name">{{ name }}</h3>
<p class="user-msg">{{ msg }}</p>
</el-col>
</el-row>
</template>
export default {
name: "mes",
props: {
nubmer: Number,
user_msg: Array,
},
computed: {
name:function(){
return this.user_msg[his.nubmer].name
},
msg:function(){
return this.user_msg[this.nubmer].msg
}
},
}
</script>
以上代碼的作用為從父主鍵獲得number、user_msg,在computed中處理將user_msg數組中的某個對象中的某值賦值給 {{ name }}、和{{ msg }}
vue-cli編譯好,啟動app后一步一步保存查看實時效果時未報錯,但是刷新頁面時報錯
Cannot read property 'name' of undefined"
解決方法
上網尋找解決方法,在該帖中獲得答案:該貼入口
異步請求獲取數據時,由於數據時異步獲取的,所以一開始是沒有該數據屬性的,這種情況下也會報這種錯誤。
比如說我這里有一個數據info,初始值為一個空對象。{{info.supports}}是不會報錯的,但是,{{info.supports.name}}這樣就會報錯了。這是為什么呢?
因為,info.supports已經是一個undefined了,你undefined.name就肯定會報錯了
代碼修改
修改 computed中代碼
computed: {
name:function(){
return ((this.user_msg||{})[this.nubmer]||{}).name
},
msg:function(){
return ((this.user_msg||{})[this.nubmer]||{}).msg
}
}
編譯通過,這樣寫在訪問對象中值的時候如果對象未undefined時,創建一個空對象。
思考:為什么在改代碼的時候,app項目效果是正常顯示的呢?而刷新頁面就報錯了。
猜測:修改代碼時,項目效果同步更新,但是未將對象重新聲明。