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

Vue在data()中用变量索引访问对象数组报cannot read property 'undefined'错误

错误根因

在Vue的data()函数执行阶段,你返回的响应式对象还没有被挂载到当前Vue实例上,此时通过this访问data中定义的其他属性,拿到的都是undefined,所以this.texts和this.currentText均为未定义,自然会抛出cannot read property 'undefined' of undefined错误。


解决方案

方案1:提前声明依赖变量(适合不需要响应式联动的场景)

把需要复用的变量提前在return语句之外声明,直接引用变量而不是通过this访问即可:

export default {
  data(){
    // 提前声明公共变量
    const initCurrentText = 0
    const initTexts = [{
        text: 'the quick brown fox jumped over the lazy dog',
        textSize: '50px'
      },{
        text: 'sphinx of black quartz judge my vow',
        textSize: '50px'
      }
    ]
    return {
      correct: 0,
      total: 0,
      currentText: initCurrentText,
      position: 0,
      userText: '',
      texts: initTexts,
      textSize: initTexts[initCurrentText].textSize
    }
  }
}

方案2:改为计算属性(更推荐,支持响应式联动)

如果后续currentText会动态变化,textSize需要跟着自动更新,直接把textSize放到computed选项中即可,这是Vue的标准用法:

export default {
  data(){
    return {
      correct: 0,
      total: 0,
      currentText: 0,
      position: 0,
      userText: '',
      texts: [{
          text: 'the quick brown fox jumped over the lazy dog',
          textSize: '50px'
        },{
          text: 'sphinx of black quartz judge my vow',
          textSize: '50px'
        }
      ]
    }
  },
  computed: {
    textSize() {
      // 此时data已挂载完成,可以正常通过this访问
      return this.texts[this.currentText].textSize
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:57:02