1.起因和需求
需要获取VideoPlayer实例来操作currentTime,代码如下:
// demo.vue
import {videoPlayer} from 'vue-video-player';
export default class demo extends Vue {
get player() {
return (this.$refs.VideoPlayer as VideoPlayer).player;
}
}
2. 异常报错
此时会提示异常:Cannot find name ‘VideoPlayer’,所以我们需要定义VideoPlayer,如何定义呢?
3 解决方案
3.1 分析VideoPlayer
我们知道VideoPlayer是一个vue组件,所以可以知道类型是HTMLBaseElement,如下:
// 定义VideoPlayer
interface VideoPlayer extends HTMLBaseElement {
player:any
}
那么,player怎么定义?
3.2 分析vue-video-player的模块包
// index.js
import videoPlayer from './player.vue'
const VueVideoPlayer = { videojs, videoPlayer, install }
// 由此知道this.$refs.VideoPlayer = player.vue组件,因此 this.$refs.VideoPlayer.player是 player.vue里的this.player
分析player.vue
// player.vue
import _videojs from 'video.js'
const videojs = window.videojs || _videojs
this.player = videojs(...)
video.js是第三方模块包,我们知道90%都可以在TypeSearch找到模块包的types,于是搜索找到:
3.2.1 安装@types/video.js
npm i @types/video.js --save-dev
3.2.2 分析@types/video.js
// index.d.ts
declare namespace videojs{}
export interface VideoJsPlayer extends videojs.Component{} // 分析发现player就是当前接口VideoJsPlayer
export interface VideoJsPlayerOptions extends videojs.ComponentOptions{}
export interface VideoJsPlayerPluginOptions {}
3.3 最终解决方案
// shims-vue.d.ts
// 这个定义模块vue-video-player
declare module 'vue-video-player';
// 定义VideoPlayer
interface VideoPlayer extends HTMLBaseElement {
player: videojs.VideoJsPlayer;
}