【发布时间】:2021-12-13 13:00:14
【问题描述】:
所以我设法注入 hls.js 以使用 nuxtjs $root 元素和this
我是这样做的(hls.client.js):
import Hls from 'hls.js';
export default (context, inject) => {
inject('myhls', Hls)
}
和 nuxt.config.js
plugins: [
'~plugins/hls.client.js',
],
从字面上看,这很好用 :-) 但我不能在 hls 事件中引用“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' DOES NOT WORK INSIDE this.hls.on
this.hls.on(this.$myhls.Events.MEDIA_ATTACHED, function () {
console.log(this.scr_arr[2]); // DOES NOT LOG
console.log("ok") // works great
});
// 'THIS' DOES NOT WORK INSIDE this.hls.on
this.hls.on(this.$myhls.Events.MANIFEST_PARSED, function (event, data) {
console.log('manifest loaded, found ' + data.levels.length + ' quality level') // WORKS
console.log("ok") // WORKS
this.audio.volume = 1 // DOES not work
});
}
},
所以我在这些事件中我不能使用 nuxtjs 'this',因为似乎有不同的范围?
我能否以某种方式在这些事件中获取“this”nuxt 范围?
【问题讨论】:
-
this.hls.attachMedia不应该是this.$myhls.attachMedia吗? -
另外,如果你想使用
this.audio.volume,使用箭头函数() =>而不是function (event, data) {。 -
@kissu this.$myhls 只是 Hls 对象。它具有公共方法 isSupported()。我尝试注入 new Hls() ,但这根本没有暴露 isSupported() 。
-
@kissu 关于 this.audio.volume 的用法,你的方法很有效,很棒。是不是因为那么它不是回调函数?
-
在块作用域(
function() {语法)中,this绑定到嵌套作用域而不是 vue 的this实例。如果您想将this保留在函数内部,请使用箭头函数(ES6),或者您可以使用const that = this并在常规function() {中使用that,如果您愿意的话。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript vue.js nuxt.js hls.js nuxtjs2