vue3 倒计时编写

通过使用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



你可能感兴趣的:(vue3 倒计时编写)