Vue中Cannot read properties of undefined (reading 'nestedArray')错误解决方法
解决Vue渲染警告:Cannot read properties of undefined (reading 'nestedArray')
问题原因
- 钩子时机错误:
beforeCreate阶段Vue实例的data属性还未挂载到this上,此时访问this.nestedArray会得到undefined,导致后续赋值逻辑失效,最终模板渲染时找不到该属性。 - 模板语法冗余:Vue模板中无需用
this访问实例属性,多余的this可能引发解析问题。
修复步骤
1. 迁移逻辑到created钩子
将数据初始化代码从beforeCreate移到created,此时data已完成挂载,可正常访问this.nestedArray:
created() { this.$store.dispatch("loadCities").then((response) => { this.cities = response; this.sortingCities = this.cities.slice(0).sort(function(a,b) { return a.row - b.row || a.col - b.col; }) this.sortingCities.map(item => { if (!this.nestedArray[item.row]) { this.nestedArray[item.row] = []; } this.nestedArray[item.row][item.col] = item; }); }); }
2. 修正模板中的this引用
模板里直接使用属性名即可,无需添加this,同时给imageId也加上可选链,避免空值报错:
<img :src="require(`../images/${nestedArray?.[row]?.[col]?.imageId}.png`)" alt="">
3. (可选)添加加载状态
因为loadCities是异步操作,数据加载完成前nestedArray为空,可在模板中添加加载提示:
<template v-if="!nestedArray.length"> <div>加载中...</div> </template> <template v-else> <img :src="require(`../images/${nestedArray?.[row]?.[col]?.imageId}.png`)" alt=""> </template>
内容的提问来源于stack exchange,提问作者oguzcan
相关产品推荐
相关产品推荐

