vue实现视频播放暂停
使用 <video> 标签实现基础控制
在 Vue 中可以通过原生 HTML5 的 <video> 标签实现视频播放和暂停功能。在模板中添加 <video> 标签并绑定 ref,通过调用 play() 和 pause() 方法控制视频。
<template>
<div>
<video ref="videoPlayer" controls>
<source src="your-video.mp4" type="video/mp4">
</video>
<button @click="playVideo">播放</button>
<button @click="pauseVideo">暂停</button>
</div>
</template>
<script>
export default {
methods: {
playVideo() {
this.$refs.videoPlayer.play();
},
pauseVideo() {
this.$refs.videoPlayer.pause();
}
}
};
</script>
使用状态管理播放/暂停切换
通过一个布尔状态变量管理播放和暂停的切换,减少重复代码。定义一个 isPlaying 变量,根据当前状态调用对应方法。
<template>
<div>
<video ref="videoPlayer" controls>
<source src="your-video.mp4" type="video/mp4">
</video>
<button @click="togglePlay">
{{ isPlaying ? '暂停' : '播放' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
isPlaying: false
};
},
methods: {
togglePlay() {
const video = this.$refs.videoPlayer;
if (this.isPlaying) {
video.pause();
} else {
video.play();
}
this.isPlaying = !this.isPlaying;
}
}
};
</script>
使用第三方库(如 Video.js)
对于更复杂的视频控制需求,可以集成第三方库如 Video.js。安装 Video.js 后,在 Vue 组件中初始化播放器并调用其 API。
npm install video.js
<template>
<div>
<video ref="videoPlayer" class="video-js"></video>
<button @click="togglePlay">
{{ isPlaying ? '暂停' : '播放' }}
</button>
</div>
</template>
<script>
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
export default {
data() {
return {
player: null,
isPlaying: false
};
},
mounted() {
this.player = videojs(this.$refs.videoPlayer, {
sources: [{
src: 'your-video.mp4',
type: 'video/mp4'
}]
});
},
methods: {
togglePlay() {
if (this.isPlaying) {
this.player.pause();
} else {
this.player.play();
}
this.isPlaying = !this.isPlaying;
}
},
beforeDestroy() {
if (this.player) {
this.player.dispose();
}
}
};
</script>
监听视频事件更新状态
通过监听 <video> 标签的 play 和 pause 事件,自动同步 isPlaying 状态。避免因用户直接操作视频控件导致状态不一致。
<template>
<div>
<video
ref="videoPlayer"
controls
@play="onPlay"
@pause="onPause"
>
<source src="your-video.mp4" type="video/mp4">
</video>
<button @click="togglePlay">
{{ isPlaying ? '暂停' : '播放' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
isPlaying: false
};
},
methods: {
togglePlay() {
const video = this.$refs.videoPlayer;
if (this.isPlaying) {
video.pause();
} else {
video.play();
}
},
onPlay() {
this.isPlaying = true;
},
onPause() {
this.isPlaying = false;
}
}
};
</script>






