【问题标题】:Conditional import in Vue componentVue组件中的条件导入
【发布时间】:2020-10-18 11:47:09
【问题描述】:

我有一个根实例,其中包含多个CustomVideo-组件(在一堆其他组件中)。 CustomVideo-component 实现了VideoJS,但并不是所有页面都有CustomVideo-component,所以我不想全局导入VideoJS。以下是页面上的组件示例:

App.js
|
|-- CustomVideo
|-- FooComponent
|-- CustomVideo
|-- BarComponent
|-- CustomVideo

在 CustomVideo 的顶部,我导入 VideoJS,如下所示:

import videojs from 'video.js';
import abLoopPlugin from 'videojs-abloop'


export default {
  name: "FeaturedVideoPlayer",
  props: {
    videoUrl: String
  }
  mounted() {
    let videoOptions = {
      sources: [
        {
          src: this.videoUrl,
          type: "video/mp4"
        }
      ],
      plugins: {
        abLoopPlugin: {
          'enabled': true
        }
      }
    };

    this.player = videojs(this.$refs.featuredVideoPlayer, videoOptions, function onPlayerReady() {});

  }

但如果有多个CustomVideo,那么我会收到控制台警告:

VIDEOJS:警告:名为“abLoopPlugin”的插件已经存在。您可能希望避免重新注册插件!

我尝试研究条件导入,但似乎不是这样做的方法。


即使我尝试将其导入app.js,即使我宁愿将其导入CustomVideo,也会收到另一个控制台错误:

尝试

import abLoopPlugin from 'videojs-abloop'
Vue.use( abLoopPlugin );

然后我得到错误:

未捕获的类型错误:无法读取未定义的属性“registerPlugin”


如何确保插件只注册一次?

【问题讨论】:

标签: javascript vue.js vuejs2 video.js


【解决方案1】:

尝试创建 abLoopPlugin 的实例。我对 vue-i18n 和其他插件采用相同的方法在全球范围内使用。比如:

import AbLoopPlugin from 'videojs-abloop'

Vue.use(AbLoopPlugin) // CHECK IF REGISTER PLUGIN ERROR PERSIST

const abLoopPlugin = new AbLoopPlugin({
   ---your settings---
})
export default abLoopPlugin

【讨论】:

    【解决方案2】:

    检查videojs.getPlugins().abLoopPlugin

    videojs.getPlugins() 返回所有已加载插件名称的符号表。在将abLoopPlugin 加载到组件中之前,您可以简单地检查它是否不在该表中:

    import videojs from 'video.js'
    
    if (!videojs.getPlugins().abLoopPlugin) {
      abLoopPlugin(window, videojs)
    }
    

    在使用ref之前等待$nextTick

    您会注意到您的视频最初在您指定的<video> 元素中不可见。这是因为refmounted() 中传递给videojs 时未定义。

    ref docs 状态:

    关于 ref 注册时间的重要说明:因为 ref 本身是作为渲染函数的结果创建的,所以您无法在初始渲染时访问它们 - 它们还不存在!

    解决办法是等到$nextTick():

    async mounted() {
      // this.$refs.featuredVideoPlayer is undefined here
      await this.$nextTick()
    
      // this.$refs.featuredVideoPlayer is the <video> here
      this.player = videojs(this.$refs.featuredVideoPlayer)
    }
    

    【讨论】:

    • 感谢您的参与。当我按照您的建议(if( !abLoopPlugin.loaded ) {)进行操作时,我仍然遇到错误。当我 console.logged abLoopPlugin 时,我可以看到它是一个函数(并且因此没有任何loaded-property。但是你的回答让我找到了答案,那就是这样做:if( ! videojs.getPlugins().abLoopPlugin ){ abLoopPlugin( window, videojs ); }。如果你编辑你的答案以包括这个(并保持对nextTick的好评,然后我会将您的答案标记为正确的解决方案。
    • @Zeth 啊,我看到了,现在我记录了它。更新了答案和演示。
    猜你喜欢
    • 2021-05-01
    • 2018-01-16
    • 1970-01-01
    • 2017-05-18
    • 2021-09-02
    • 2019-04-23
    • 2017-10-11
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多