Vue实现换视频背景
Vue实现动态视频背景
安装video.js和vue-video-player依赖
npm install video.js vue-video-player
在组件中引入并注册
import { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'
基本视频背景实现
模板部分添加video-player组件
<video-player
ref="videoPlayer"
class="video-player-box"
:options="playerOptions"
@ready="onPlayerReady"
/>
配置播放器选项
data() {
return {
playerOptions: {
autoplay: true,
muted: true,
loop: true,
fluid: true,
sources: [{
type: "video/mp4",
src: require("@/assets/bg-video.mp4")
}]
}
}
}
全屏背景样式处理
添加CSS样式使视频作为背景
.video-js {
position: fixed;
right: 0;
bottom: 0;
min-width: 100%;
min-height: 100%;
z-index: -1;
}
动态切换视频源
实现方法更新视频源
methods: {
changeVideo(newSrc) {
this.playerOptions.sources[0].src = newSrc
this.$refs.videoPlayer.player.src(newSrc)
}
}
移动端兼容处理
添加playsinline属性
playerOptions: {
playsinline: true,
// 其他配置...
}
性能优化建议
预加载视频资源
mounted() {
const video = document.createElement('video')
video.src = require('@/assets/bg-video.mp4')
video.load()
}
使用WebM格式减小体积
sources: [
{
type: "video/webm",
src: require("@/assets/bg-video.webm")
},
{
type: "video/mp4",
src: require("@/assets/bg-video.mp4")
}
]






