美文网首页
vue3 倒计时编写

vue3 倒计时编写

作者: Epat | 来源:发表于2021-12-08 10:40 被阅读0次

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

    相关文章

      网友评论

          本文标题:vue3 倒计时编写

          本文链接:https://www.haomeiwen.com/subject/dfttfrtx.html