通過使用vue Composition-Api 對(duì)倒計(jì)時(shí)進(jìn)行封裝灯谣,讓倒計(jì)時(shí)的使用更加的靈活
1. 編寫 countDown.js
import { reactive, onBeforeUnmount } from 'vue'
export default function countDown(count = 60) {
let state = reactive({
count: 0,
timer: null
})
/**
* 開始倒計(jì)時(shí)
*/
function start() {
clear()
state.count = count
state.timer = setInterval(() => {
state.count--
if (state.count <= 0) {
clear()
}
}, 1000)
}
/**
* 清除倒計(jì)時(shí)
*/
function clear() {
if (state.timer) {
clearInterval(state.timer)
}
}
onBeforeUnmount(() => {
clear()
})
return {
state,
start
}
}
2. 使用countDown.js
<template>
倒計(jì)時(shí)A: {{ countdownAState.count }}
倒計(jì)時(shí)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>