[英]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)
}
尝试创建 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.