Nuxt插件注入hls.js后事件回调无法访问Vue的this实例如何解决
问题根源
回调使用普通function声明时,this会指向触发回调的hls实例,而非外层的Vue组件实例,因此无法访问到Vue实例上的属性和方法。
解决方案
方案1:使用箭头函数(推荐)
箭头函数不会创建独立的this作用域,会继承外层代码块的this指向,直接替换回调的普通函数声明即可:
playHls() { this.playing = true if(this.$myhls.isSupported()) { this.hls = new this.$myhls(); this.audio = new Audio(''); this.hls.attachMedia(this.audio); this.hls.loadSource(this.scr_arr[2]); this.audio.play() this.hls.on(this.$myhls.Events.MEDIA_ATTACHED, () => { console.log(this.scr_arr[2]); console.log("ok") }); this.hls.on(this.$myhls.Events.MANIFEST_PARSED, (event, data) => { console.log('manifest loaded, found ' + data.levels.length + ' quality level') console.log("ok") this.audio.volume = 1 }); } },
方案2:提前缓存Vue实例指向
在方法开头将Vue实例存到局部变量中,回调内直接通过该变量访问实例属性,兼容性最好:
playHls() { const vm = this vm.playing = true if(vm.$myhls.isSupported()) { vm.hls = new vm.$myhls(); vm.audio = new Audio(''); vm.hls.attachMedia(vm.audio); vm.hls.loadSource(vm.scr_arr[2]); vm.audio.play() vm.hls.on(vm.$myhls.Events.MEDIA_ATTACHED, function () { console.log(vm.scr_arr[2]); console.log("ok") }); vm.hls.on(vm.$myhls.Events.MANIFEST_PARSED, function (event, data) { console.log('manifest loaded, found ' + data.levels.length + ' quality level') console.log("ok") vm.audio.volume = 1 }); } },
方案3:手动绑定this指向
通过bind方法手动将回调的this绑定为外层Vue实例:
this.hls.on(this.$myhls.Events.MEDIA_ATTACHED, function () { console.log(this.scr_arr[2]); console.log("ok") }.bind(this)); this.hls.on(this.$myhls.Events.MANIFEST_PARSED, function (event, data) { console.log('manifest loaded, found ' + data.levels.length + ' quality level') console.log("ok") this.audio.volume = 1 }.bind(this));
内容的提问来源于stack exchange,提问作者mahatmanich
相关产品推荐
相关产品推荐

