Nuxt.js 3使用reactive()访问嵌套属性报undefined读取错误
报错原因
TypeScript 的类型标注仅在编译阶段做校验,不会自动初始化声明的可选属性。你用reactive<FormInterface>({})创建响应式对象时,运行时的初始值就是纯空对象,ruleForm.endereco实际值为undefined,此时直接访问ruleForm.endereco.cep本质是读取undefined上的cep属性,就会触发Cannot read properties of undefined的运行时错误。
修复方法
你可以任选以下一种符合业务场景的方案修复:
- 初始化响应式对象时补全嵌套层级的默认值
let ruleForm = reactive<FormInterface>({ // 给嵌套的endereco设置空对象默认值 endereco: {} })
这种写法下初始状态ruleForm.endereco是空对象而非undefined,访问cep得到undefined,模板会正常渲染空内容不会抛错。
- 模板中使用可选链操作符做安全访问,不需要修改初始化逻辑
<template> <div> <span> {{ ruleForm.endereco?.cep }} </span> </div> </template>
可选链?.会在左侧操作数为null/undefined时直接返回undefined,终止后续属性读取,从根源避免属性访问报错。
- 如果表单数据是后续通过接口请求异步赋值的,也可以在模板中加
v-if判断,等嵌套对象存在后再渲染对应内容:
<span v-if="ruleForm.endereco"> {{ ruleForm.endereco.cep }} </span>
内容的提问来源于stack exchange,提问作者marcelo.delta
相关产品推荐
相关产品推荐

