vue实现视频观看时长
监听视频播放事件
使用Vue的@play事件监听视频开始播放,结合@timeupdate实时更新当前播放时间。在<video>标签上绑定事件:
<template>
<video
ref="videoPlayer"
@play="onPlay"
@pause="onPause"
@timeupdate="onTimeUpdate"
src="video.mp4"
></video>
</template>
记录播放时间
通过currentTime属性获取当前播放进度,并计算累计时长。在Vue组件的data中定义变量存储时间:

data() {
return {
startTime: 0,
currentTime: 0,
totalWatchedTime: 0,
isPlaying: false
};
},
methods: {
onPlay() {
this.startTime = Date.now();
this.isPlaying = true;
},
onPause() {
if (this.isPlaying) {
const endTime = Date.now();
this.totalWatchedTime += (endTime - this.startTime) / 1000;
this.isPlaying = false;
}
},
onTimeUpdate() {
this.currentTime = this.$refs.videoPlayer.currentTime;
}
}
防抖处理频繁更新
为避免@timeupdate事件触发过于频繁,使用Lodash的debounce函数优化性能:

import { debounce } from 'lodash';
methods: {
onTimeUpdate: debounce(function() {
this.currentTime = this.$refs.videoPlayer.currentTime;
}, 500)
}
持久化存储时长
通过localStorage或API请求保存累计观看时长,确保页面刷新后数据不丢失:
onPause() {
if (this.isPlaying) {
const endTime = Date.now();
this.totalWatchedTime += (endTime - this.startTime) / 1000;
localStorage.setItem('videoWatchedTime', this.totalWatchedTime);
this.isPlaying = false;
}
},
mounted() {
const savedTime = localStorage.getItem('videoWatchedTime');
if (savedTime) {
this.totalWatchedTime = parseFloat(savedTime);
}
}
完整组件示例
整合以上逻辑的完整Vue组件代码:
<template>
<div>
<video
ref="videoPlayer"
@play="onPlay"
@pause="onPause"
@timeupdate="onTimeUpdate"
src="video.mp4"
></video>
<p>已观看:{{ totalWatchedTime.toFixed(2) }}秒</p>
</div>
</template>
<script>
import { debounce } from 'lodash';
export default {
data() {
return {
startTime: 0,
totalWatchedTime: 0,
isPlaying: false
};
},
methods: {
onPlay() {
this.startTime = Date.now();
this.isPlaying = true;
},
onPause() {
if (this.isPlaying) {
const endTime = Date.now();
this.totalWatchedTime += (endTime - this.startTime) / 1000;
localStorage.setItem('videoWatchedTime', this.totalWatchedTime);
this.isPlaying = false;
}
},
onTimeUpdate: debounce(function() {
this.currentTime = this.$refs.videoPlayer.currentTime;
}, 500)
},
mounted() {
const savedTime = localStorage.getItem('videoWatchedTime');
if (savedTime) {
this.totalWatchedTime = parseFloat(savedTime);
}
}
};
</script>






