Vue.js异步方法中如何正确访问this?
Vue.js异步方法中
this指向问题的解决办法 问题原因拆解
- 第一个报错
Unexpected reserved word 'await':使用await的方法必须声明为async,普通方法直接用await不符合JavaScript语法规则。 - 第二个报错
Cannot read properties of undefined (reading 'book'):箭头函数不会绑定自身的this,在Vue组件的methods中使用箭头函数时,this无法指向组件实例,自然无法读取实例上的book属性。
正确代码写法
不要用箭头函数,直接给普通方法添加async关键字即可,这样this会正常指向Vue组件实例:
如果方法需要接收外部参数:
methods: { async playRecording(path) { return await this.getAudioUrl(path) } }
如果方法要访问组件自身的book属性:
methods: { async playRecording() { const path = '/recordings/' + this.book return await this.getAudioUrl(path) } }
核心注意点
Vue组件的methods必须使用普通函数声明(或函数表达式),不能用箭头函数,这样Vue才能自动将this绑定到组件实例上。只要给方法加上async关键字,就能在方法内部正常使用await调用异步函数,同时this的指向完全正常。
内容的提问来源于stack exchange,提问作者etayluz
相关产品推荐
相关产品推荐

