Vue实现换视频背景
Vue实现动态视频背景
创建Vue组件VideoBackground.vue
<template>
<div class="video-background">
<video
ref="videoPlayer"
autoplay
loop
muted
playsinline
:poster="poster"
class="video-content"
>
<source :src="videoSrc" type="video/mp4">
</video>
<div class="content-overlay">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
videoSrc: {
type: String,
required: true
},
poster: {
type: String,
default: ''
}
},
mounted() {
this.$refs.videoPlayer.play().catch(e => {
console.log('Autoplay prevented:', e)
})
}
}
</script>
<style scoped>
.video-background {
position: relative;
width: 100%;
height: 100vh;
overflow: hidden;
}
.video-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -1;
}
.content-overlay {
position: relative;
z-index: 1;
color: white;
padding: 2rem;
}
</style>
使用组件方法
在父组件中引入并配置
<template>
<div>
<VideoBackground
videoSrc="/path/to/your/video.mp4"
poster="/path/to/poster-image.jpg"
>
<h1>页面主要内容</h1>
<p>其他内容元素</p>
</VideoBackground>
</div>
</template>
<script>
import VideoBackground from './components/VideoBackground.vue'
export default {
components: {
VideoBackground
}
}
</script>
视频切换功能实现
扩展组件支持动态切换
<script>
export default {
// ...原有props
watch: {
videoSrc(newVal) {
const video = this.$refs.videoPlayer
video.src = newVal
video.load()
video.play().catch(e => {
console.log('Playback error:', e)
})
}
}
}
</script>
响应式优化方案
添加媒体查询适应移动设备
@media (max-width: 768px) {
.video-background {
height: 50vh;
}
.video-content {
display: none;
}
.video-background {
background: url('/path/to/mobile-fallback.jpg') center/cover no-repeat;
}
}
性能优化技巧
预加载视频资源
<script>
export default {
// ...原有代码
methods: {
preloadVideo() {
const link = document.createElement('link')
link.rel = 'preload'
link.href = this.videoSrc
link.as = 'video'
document.head.appendChild(link)
}
},
created() {
this.preloadVideo()
}
}
</script>
浏览器兼容处理
添加多种视频格式支持
<template>
<video>
<source :src="videoSrc" type="video/mp4">
<source :src="webmSrc" type="video/webm">
<source :src="oggSrc" type="video/ogg">
</video>
</template>
<script>
export default {
props: {
webmSrc: String,
oggSrc: String
}
}
</script>






