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

读取object[key].value出现undefined,如何动态为对象添加ID属性?

问题原因
  • 你最初的写法逻辑有误:你先把this.cars.id赋值为字符串"test-01-test",此时this.cars.id是字符串类型,不是对象,自然不存在["test-01-test"]属性,才会抛出Cannot set property 'color' of undefined的错误。
  • 如果你用的是Vue2,直接给响应式对象新增不存在的属性,不会触发视图更新,需要用Vue提供的$set方法处理。
实现方案

1. 初始data定义

你不需要预先在cars里写固定的id键,直接把cars初始化为空对象即可:

data() {
  return {
    cars: {}
  }
}

2. 手动添加固定ID的车辆数据

在mounted里添加test-01-test的写法如下:

mounted() {
  // Vue2写法,用$set保证响应式
  this.$set(this.cars, 'test-01-test', {
    brand: 'anybrand',
    color: 'blue'
  })
  // Vue3不需要$set,直接赋值即可
  // this.cars['test-01-test'] = { brand: 'anybrand', color: 'blue' }

  console.log(this.cars["test-01-test"].color) // 输出blue
}

3. 动态添加用户输入的车辆ID

假设你拿到用户输入的ID存在变量newId里,添加逻辑如下:

// 示例:从弹窗获取用户输入的ID
const newId = prompt('请输入新的车辆ID')
if (newId) { // 判空避免生成无效键
  // Vue2写法
  this.$set(this.cars, newId, {
    brand: 'anybrand',
    color: 'blue'
  })
  // Vue3写法
  // this.cars[newId] = { brand: 'anybrand', color: 'blue' }
}

处理完成后生成的cars对象完全符合你需要的结构,也可以正常用this.cars[车辆ID].color的方式读取对应属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:39:03