You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue使用localStorage存储表单值为空时输入框显示undefined如何解决

问题原因

你的问题核心出在空值没有做兜底处理:

  • 表单字段未输入内容时,对应this.model下的属性值为undefined,直接存入localStorage时,会被自动转为字符串"undefined"
  • 后续读取时,字符串"undefined"属于真值,会通过if (localStorage.xxx)的判断,被直接赋值给表单绑定的model属性,输入框就会显示undefined内容
  • 另外你的代码还遗漏了schema中定义的Basement字段的读写逻辑,该字段也会出现同样的问题

修复方案

  1. 初始化model时给所有表单字段设置默认空字符串,避免初始值为undefined
// 组件data选项中初始化model
data() {
  return {
    model: {
      Garages: '',
      Basement: '',
      Roof: '',
      Exterior: '',
      // 其余所有表单用到的字段都统一设置默认值为空字符串
    }
  }
}
  1. 存储逻辑添加空值兜底,未输入内容时存空字符串
// 所有存储字段都改用 ?? 运算符做兜底
localStorage.Garages = this.model.Garages ?? '';
localStorage.Basement = this.model.Basement ?? '';
localStorage.Roof = this.model.Roof ?? '';
// 其余字段都按上述格式修改,记得补上遗漏的Basement字段
  1. 读取逻辑添加兼容判断,避免历史存储的"undefined"字符串被赋值
// 所有读取字段都加判断,过滤掉值为"undefined"的情况
this.model.Garages = (localStorage.Garages && localStorage.Garages !== 'undefined') ? localStorage.Garages : '';
this.model.Basement = (localStorage.Basement && localStorage.Basement !== 'undefined') ? localStorage.Basement : '';
// 其余字段都按上述格式修改,记得补上遗漏的Basement字段

内容的提问来源于stack exchange,提问作者Inayat Kazi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:57:04