美文网首页
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 倒计时编写

    通过使用vue Composition-Api 对倒计时进行封装,让倒计时的使用更加的灵活 1. 编写 count...

  • vue3和vue2的区别及vue3核心语法

    一、 vue3和vue2的区别 api的区别vue2: vue3 vue3底层用的typescript语言编写,v...

  • vue3.0你知道有哪些改进

    Vue3 采用了TS来编写 [支持 Composition API]http://caibaojian.com/v...

  • 5. vue3.0 解决了什么问题?

    一、 Vue3 的性能提升 整个vue3的代码库将代码重新编写成了一系列分开的实现不同功能的 module 代码打...

  • Vue3 + vite svg 组件

    Vue3 + vite 编写svg组件,本质上和vue2 + webpack 没有多大出入,唯一不同的是得编写一个...

  • Vue3 script-setup语法糖

    注意: 该语法糖现在正处于实验阶段作用: 简化代码编写 Vue3 script-setup 超清新单文件写法 - ...

  • shell脚本从入门到精通

    一、Shell脚本编写格式 二、回收站 三、当前内存使用率 四、倒计时程序的编写 五、水果商店 六、Shell基本...

  • TypeScript14(泛型)

    泛型在TypeScript是很重要的东西 例如vue3 是用ts编写的 里面用到了非常多的泛型 函数泛型 我写了两...

  • vue3项目

    安装过程 1、安装vue3 2、创建vue3项目 3、启动vue3项目 4、vue3加载过程 加载index.ht...

  • Vue3 的新特性

    目录 Vue3 的新特性 Vue3 的新特性(二) —— Composition-Api Vue3 的新特性(三)...

网友评论

      本文标题:vue3 倒计时编写

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