vue 实现一个定时器组件
- 效果图
- 子组件
- 父组件
效果图
子组件
新建一个timer.vue文件
<template><span :class="{red: string >= 600}">{{ string | formatDurationS }}</span>
</template>
<script>export default {name: 'timer',props: {startTimer: {type: [String, Number],default: 0},currentTimer: {type: [String, Number],default: 0}},data() {return {string: '--:--:--', // '00:00:00',step: 0,intervalName: ''}},watch: {currentTimer: {handler: function(nev, oldv) {if (this.intervalName) {clearInterval(this.intervalName)}this.step = this.startTimerlet _str = Math.round((this.currentTimer - this.startTimer) / 1000)this.string = _str < 0 ? 0 : _strthis.intervalName = setInterval(() => {this.string++}, 1000)},immediate: true}},beforeDestroy() {clearInterval(this.intervalName)this.intervalName = null}
}</script>
<style scoped lang="less">
.red {color: #F03E3E;
}
</style>
父组件
导入子组件并注册
<TIMER ref="timerFun" :currentTimer="timeStamp" :startTimer="item.actionTime"></TIMER>import TIMER from '@/components/timer.vue'timeStamp: Date.now(),components: {TIMER
}
- startTimer: 开始计时的时间戳
- currentTimer: 当前本地时间时间戳
- 两者的差值就是起始的持续时间