Nuxt插件无法访问功能块中的Vue&39;s;This实例 [英] Nuxt plugin cannot access Vue's 'this' instance in function blocks

查看:29
本文介绍了Nuxt插件无法访问功能块中的Vue&39;s;This实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经设法注入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.on(this.$myhls.Events.MANIFEST_PARSED, function (event, data) {

进入

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

要将this上下文绑定到Vue应用,否则它的作用域将限制在挡路作用域的上下文中。

这篇关于Nuxt插件无法访问功能块中的Vue&39;s;This实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆