cameraItem.vue 2.08 KB
<template>
  <div class="go-content-box" :style="{ width: w + 'px', height: h + 'px' }">
    <video :id="`my-player${index}`" ref="videoRef" class="video-js my-video vjs-theme-city vjs-big-play-centered">
      <source :src="sourceSrc" />
    </video>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, onUnmounted, watch } from 'vue'
import videojs from 'video.js'
import type { VideoJsPlayerOptions } from 'video.js'
import 'video.js/dist/video-js.min.css'

const props = defineProps({
  sourceSrc: {
    type: String
  },
  w: {
    type: Number,
    default: 300
  },
  h: {
    type: Number,
    default: 300
  },
  index: {
    type: Number
  }
})

// video标签
const videoRef = ref<HTMLElement | null>(null)

// video实例对象
let videoPlayer: videojs.Player | null = null

//options配置
const options: VideoJsPlayerOptions = {
  language: 'zh-CN', // 设置语言
  controls: true, // 是否显示控制条
  preload: 'auto', // 预加载
  autoplay: true, // 是否自动播放
  fluid: false, // 自适应宽高
  src: props.sourceSrc, // 要嵌入的视频源的源 URL
  muted: true,
  userActions: {
    hotkeys: true
  }
}

// 初始化videojs
const initVideo = () => {
  if (videoRef.value) {
    // 创建 video 实例
    videoPlayer = videojs(videoRef.value, options)
  }
}

watch(
  () => props.sourceSrc,
  (newData: any) => {
    // props.sourceSrc = newData
    videoPlayer?.src(newData) as any
    videoPlayer?.play()
  },
  {
    immediate: true
  }
)

onMounted(() => {
  initVideo()
})

onUnmounted(() => {
  handleVideoDispose()
})

//播放
const handleVideoPlay = () => videoPlayer?.play()

const handleVideoDispose = () => videoPlayer?.dispose() && videoPlayer?.pause()
//暂停
defineExpose({
  handleVideoPlay,
  handleVideoDispose
})
</script>

<style lang="scss" scoped>
.go-content-box {
  display: flex;
  align-items: center;
  justify-content: center;
  .my-video {
    width: 100% !important;
    height: 100% !important;
    position: relative;
  }
}
</style>