vue插视频怎么实现
使用HTML5 video标签
在Vue中嵌入视频最基础的方法是使用HTML5的<video>标签。直接在模板中添加<video>元素,并设置src属性指向视频文件路径。支持MP4、WebM等格式。
<template>
<video controls width="500">
<source src="@/assets/video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</template>
controls属性显示播放控件,width调整视频宽度。@/assets/指向项目中的静态资源目录。
动态绑定视频源
通过Vue的响应式数据动态绑定视频源,适合需要切换不同视频的场景。在data中定义视频路径,用v-bind绑定到src属性。
<template>
<video controls :src="currentVideo"></video>
<button @click="changeVideo">切换视频</button>
</template>
<script>
export default {
data() {
return {
currentVideo: require('@/assets/video1.mp4'),
videos: [
require('@/assets/video1.mp4'),
require('@/assets/video2.mp4')
]
}
},
methods: {
changeVideo() {
this.currentVideo = this.videos[1];
}
}
}
</script>
使用第三方库(如vue-video-player)
对于更复杂的视频播放需求(如自定义控件、直播流),可以使用第三方库。以vue-video-player为例,它基于Video.js封装。
安装依赖:
npm install vue-video-player video.js
在组件中使用:
<template>
<video-player :options="playerOptions" />
</template>
<script>
import 'video.js/dist/video-js.css'
import { videoPlayer } from 'vue-video-player'
export default {
components: {
videoPlayer
},
data() {
return {
playerOptions: {
autoplay: false,
controls: true,
sources: [{
src: require('@/assets/video.mp4'),
type: 'video/mp4'
}]
}
}
}
}
</script>
嵌入外部视频(如YouTube)
通过iframe嵌入YouTube等平台视频。复制平台提供的分享代码,或动态生成iframe的src。
<template>
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/VIDEO_ID"
frameborder="0"
allowfullscreen
></iframe>
</template>
移动端适配注意事项
在移动设备上,部分浏览器会阻止自动播放。需添加playsinline和muted属性,并可能需要用户交互触发播放。
<video controls playsinline muted>
<source src="@/assets/video.mp4" type="video/mp4">
</video>






