欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用Vue3实现简单易懂的倒计时功能

最编程 2024-02-22 20:10:04
...

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

推荐阅读