vue3+ts中video使用问题记录

300 阅读1分钟

记录一下不长记性的问题,之前遇见过了但没记录忘记了

<template>
  <div class="video-show">
    <video ref="videoRef" id="video" width="450" height="250" muted loop>
      <source src="地址" type="video/mp4" />
    </video>
  </div>
</template>

<script lang="ts" setup>
import { ref, watchEffect, onMounted } from 'vue'
// video
const videoRef = ref<HTMLVideoElement | null>(null)

onMounted(() => {
  videoRef.value = document.getElementById('video') as HTMLVideoElement
})
watchEffect(() => {
  if (其它条件&&videoRef.value) {
    videoRef.value.play()
  }
})
</script>
<style lang="scss" scoped>
.video-show {
  width: 100%;
  height: 100%;
}
</style>

1. 错误描述: Cannot read properties of null (reading 'play')

  • 原因:watchEffect中没加videoRef.value判断条件

  • 注意videoref声明类型时候不要用HTMLElement会产生Property 'play' does not exist on type 'HTMLElement'

2. 错误描述:Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document

  • 原因:浏览器限制不能自动播放音频视频
  • 解决方法:

1.设置浏览器允许播放声音源
2.<video muted/>