vue3 倒计时编写
2021-12-08 本文已影响0人
Epat
通过使用vue Composition-Api 对倒计时进行封装,让倒计时的使用更加的灵活
1. 编写 countDown.js
import { reactive, onBeforeUnmount } from 'vue'
export default function countDown(count = 60) {
let state = reactive({
count: 0,
timer: null
})
/**
* 开始倒计时
*/
function start() {
clear()
state.count = count
state.timer = setInterval(() => {
state.count--
if (state.count <= 0) {
clear()
}
}, 1000)
}
/**
* 清除倒计时
*/
function clear() {
if (state.timer) {
clearInterval(state.timer)
}
}
onBeforeUnmount(() => {
clear()
})
return {
state,
start
}
}
2. 使用countDown.js
<template>
倒计时A: {{ countdownAState.count }}
倒计时B: {{ countdownBState.count }}
</template>
<script>
export default {
setup() {
const { state: countdownAState, start: startTimeoutA } = countDown(60)
const { state: countdownBState, start: startTimeoutB } = countDown(120)
return {
countdownAState,
startTimeoutA,
countdownBState,
startTimeoutB
}
},
mounted () {
this.startTimeoutA()
this.startTimeoutB()
}
}
</script>