页面效果:动态计时
计时组件代码
<template>
<!-- 时分秒正计时器 -->
<div class="father">
<span>{{ data.one }}<span>:</span></span>
<span>{{ data.two }}<span>:</span></span>
<span>{{ data.three }}</span>
</div>
</template>
<script setup lang="ts">
import { reactive, watch } from 'vue'
const props = defineProps({
// 计时器开始1 停止2
isStart: {
type: Number,
default: 0
},
})
const emit = defineEmits(['onStop', 'onStart'])
type dataType = {
flag: any;
one: string | number;
two: string | number;
three: string | number;
abc: number;
cde: number;
efg: number
}
const data = reactive<dataType>({
flag: null,
one: '00', // 时
two: '00', // 分
three: '00', // 秒
abc: 0, // 秒的计数
cde: 0, // 分的计数
efg: 0, // 时的计数
})
watch(() => data.three, (newVal) => {
emit('onStart', { hour: data.one, min: data.two, sec: newVal })
})
watch(() => props.isStart, (newVal) => {
if (newVal == 1) {
startHandler()
} else if (newVal == 2) {
endHandler()
emit('onStop', { hour: data.one, min: data.two, sec: data.three })
// 清除时间
data.one = '00';
data.two = '00';
data.three = '00';
data.abc = 0;
data.cde = 0;
data.efg = 0;
}
})
const startHandler = () => {
data.flag = setInterval(() => {
if (data.three === 60 || data.three === '60') {
data.three = '00';
data.abc = 0;
if (data.two === 60 || data.two === '60') {
data.two = '00';
data.cde = 0;
if (data.efg + 1 <= 9) {
data.efg++;
data.one = '0' + data.efg;
} else {
data.efg++;
data.one = data.efg;
}
} else {
if (data.cde + 1 <= 9) {
data.cde++;
data.two = '0' + data.cde;
} else {
data.cde++;
data.two = data.cde;
}
}
} else {
if (data.abc + 1 <= 9) {
data.abc++;
data.three = '0' + data.abc;
} else {
data.abc++;
data.three = data.abc;
}
}
}, 1000)
}
const endHandler = () => {
data.flag = clearInterval(data.flag)
}
</script>
<style lang="scss" scoped></style>
使用组件:timeInfo就是返回的动态的时间
<!-- 计时器组件 -->
<TimeCount :isStart="data.isStart" @onStart="onStart" @onStop="onStop"></TimeCount>
const data = reactive({
isStart: 0,
timeInfo: {},
})
// 计时中
const onStart = (val: Object) => {
data.timeInfo = val
}
// 计时停止
const onStop = (val: Object) => {
data.timeInfo = val
}