簡體   English   中英

Vue組件中的條件導入

[英]Conditional import in Vue component

我有一個根實例,其中包含多個CustomVideo組件(在一堆其他組件中)。 CustomVideo實現了 VideoJS ,但並非所有頁面上都有CustomVideo ,因此我不想全局導入 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”


如何確保插件只注冊一次?

檢查videojs.getPlugins().abLoopPlugin

videojs.getPlugins()返回所有已加載插件名稱的符號表。 在將 abLoopPlugin 加載到組件中之前,您可以簡單地檢查abLoopPlugin是否不在該表中:

import videojs from 'video.js'

if (!videojs.getPlugins().abLoopPlugin) {
  abLoopPlugin(window, videojs)
}

在使用ref之前等待$nextTick

您會注意到您的視頻最初在您指定的<video>元素中不可見。 這是因為當您在mounted()中將 ref 傳遞給videojs時,該ref是未定義的。

ref文檔state:

關於 ref 注冊時間的重要說明:因為 ref 本身是作為渲染 function 的結果創建的,所以您無法在初始渲染時訪問它們 - 它們還不存在!

解決方案是等到$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)
}

在 Vue 中使用 videojs-abloop 編輯

嘗試創建 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM