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

Vue开发中如何从async异步方法内修改data中定义的响应式变量值

问题原因
  • 核心错误是你访问了不存在的self.data属性:在Vue的选项式API中,data()函数返回的所有字段会直接挂载到组件实例上,不需要通过.data二次访问,你要操作的数组是cards,所以正确的访问路径是self.cards[0]
  • 额外注意:你声明了async关键字但没用到await语法,属于冗余写法,要么保留.then去掉async,要么用await写法更简洁,也不需要额外声明self变量存this指向(箭头函数会继承外层作用域的this,不用额外处理指向)
修正后的代码

保留.then写法的修正版本

methods: {
  getEosComp() {
    this.loading = true
    collectDataService.getMakEosTotalComp()
    .then(data => {
      // 直接通过this访问cards数组即可,箭头函数已绑定外层this
      this.cards[0].comps = data
      this.loading = false
    })
  },
}

更简洁的async/await写法

methods: {
  async getEosComp() {
    this.loading = true
    const data = await collectDataService.getMakEosTotalComp()
    this.cards[0].comps = data
    this.loading = false
  },
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 21:45:04