所以我設法注入 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',因為似乎有不同的范圍?
我可以以某種方式在這些事件中獲得“這個”nuxt 范圍嗎?
uj5u.com熱心網友回復:
替換您的功能,例如
this.hls.on(this.$myhls.Events.MANIFEST_PARSED, function (event, data) {
進入
this.hls.on(this.$myhls.Events.MANIFEST_PARSED, (event, data) => {
保持this背景關系系結到 Vue 應用程式,否則它將被限制在塊范圍的背景關系中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/340039.html
