【问题标题】:Nuxt plugin cannot access Vue's 'this' instance in function blocksNuxt 插件无法在功能块中访问 Vue 的“this”实例
【发布时间】: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


【解决方案1】:

替换你的函数

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

进入

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

保持this 上下文绑定到 Vue 应用程序,否则它将被限定为块作用域的上下文。

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 1970-01-01
    • 2018-12-19
    • 2020-08-25
    • 2016-08-25
    • 2021-04-14
    • 2015-06-17
    相关资源
    最近更新 更多