所以我已经设法注入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'下一个作用域吗?
将函数替换为
this.hls.on(this.$myhls.Events.MANIFEST_PARSED, function (event, data) {
到
this.hls.on(this.$myhls.Events.MANIFEST_PARSED, (event, data) => {
将this
上下文绑定到Vue应用程序,否则它将被限定在块作用域的上下文中。