Home > Mobile >  Nuxt plugin cannot access Vue's 'this' instance in function blocks
Nuxt plugin cannot access Vue's 'this' instance in function blocks

Time:10-28

So I have managed to inject hls.js to work with nuxtjs $root element and this

I did so doing it like this (hls.client.js):

import Hls from 'hls.js';

export default (context, inject) => {
  inject('myhls', Hls)
}

and nuxt.config.js

plugins: [
  '~plugins/hls.client.js',
],

This works great, literally :-) but I can't reference 'this' in the hls events.

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   
        });
      }
    },

So I in these Events I can't use nuxtjs 'this', cause there seems to be a different scope?

Can I somehow get 'this' nuxt scope inside these Events?

CodePudding user response:

Replace your functions like

this.hls.on(this.$myhls.Events.MANIFEST_PARSED, function (event, data) {

into

this.hls.on(this.$myhls.Events.MANIFEST_PARSED, (event, data) => {

to keep the this context tied to the Vue app, otherwise it will be scoped to the context of the block scope.

  • Related