vue实现视频
Vue 实现视频播放功能
使用 HTML5 <video> 标签
Vue 可以直接使用 HTML5 的 <video> 标签实现视频播放。通过绑定 src 属性和控制播放状态,可以轻松实现视频功能。

<template>
<div>
<video ref="videoPlayer" controls :src="videoSrc" @play="onPlay" @pause="onPause"></video>
<button @click="togglePlay">{{ isPlaying ? 'Pause' : 'Play' }}</button>
</div>
</template>
<script>
export default {
data() {
return {
videoSrc: 'path/to/video.mp4',
isPlaying: false
}
},
methods: {
togglePlay() {
if (this.isPlaying) {
this.$refs.videoPlayer.pause()
} else {
this.$refs.videoPlayer.play()
}
},
onPlay() {
this.isPlaying = true
},
onPause() {
this.isPlaying = false
}
}
}
</script>
使用第三方库(如 video.js)
如果需要更丰富的功能(如自定义控件、字幕支持等),可以集成 video.js 或其他视频播放库。

<template>
<div>
<video ref="videoPlayer" class="video-js"></video>
</div>
</template>
<script>
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
export default {
data() {
return {
player: null
}
},
mounted() {
this.player = videojs(this.$refs.videoPlayer, {
controls: true,
sources: [{
src: 'path/to/video.mp4',
type: 'video/mp4'
}]
})
},
beforeDestroy() {
if (this.player) {
this.player.dispose()
}
}
}
</script>
实现视频流(如 HLS/DASH)
对于流媒体视频(如 .m3u8 或 .mpd 格式),可以使用 hls.js 或 dash.js 库。
<template>
<div>
<video ref="videoPlayer" controls></video>
</div>
</template>
<script>
import Hls from 'hls.js'
export default {
mounted() {
const videoSrc = 'path/to/stream.m3u8'
const video = this.$refs.videoPlayer
if (Hls.isSupported()) {
const hls = new Hls()
hls.loadSource(videoSrc)
hls.attachMedia(video)
hls.on(Hls.Events.MANIFEST_PARSED, () => {
video.play()
})
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = videoSrc
video.addEventListener('loadedmetadata', () => {
video.play()
})
}
}
}
</script>
自定义视频控件
可以通过 Vue 的响应式特性自定义视频控件,例如进度条、音量控制等。
<template>
<div>
<video ref="videoPlayer" :src="videoSrc" @timeupdate="updateProgress"></video>
<div class="controls">
<input type="range" v-model="progress" min="0" max="100" @input="seekTo">
<button @click="toggleMute">{{ isMuted ? 'Unmute' : 'Mute' }}</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
videoSrc: 'path/to/video.mp4',
progress: 0,
isMuted: false
}
},
methods: {
updateProgress() {
const video = this.$refs.videoPlayer
this.progress = (video.currentTime / video.duration) * 100
},
seekTo() {
const video = this.$refs.videoPlayer
video.currentTime = (this.progress / 100) * video.duration
},
toggleMute() {
const video = this.$refs.videoPlayer
video.muted = !video.muted
this.isMuted = video.muted
}
}
}
</script>
以上方法可以根据需求选择或组合使用,实现不同复杂度的视频播放功能。






