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
相关产品推荐
相关产品推荐

