Vue 3 的倒数/倒数计时器钩子 - vue-timer-hook

Vue 3 的倒数/倒数计时器钩子 - vue-timer-hook
插件名称 vue-timer-hook
发布时间 2021年8月22日
插件作者 riderx

用于处理 Vue 组件中的倒数计时器、秒表和时间逻辑/状态的自定义计时器挂钩。

使用:

1. 使用useTimer钩子创建倒数计时器。

import { defineComponent, watchEffect, onMounted } from "vue";
import { useTimer } from 'vue-timer-hook';
export default defineComponent({
  name: "Home",
  setup() {
    const time = new Date();
    time.setSeconds(time.getSeconds() + 600); // 10 minutes timer
    const timer = useTimer(time);
    const restartFive = () => {
        // Restarts to 5 minutes timer
        const time = new Date();
        time.setSeconds(time.getSeconds() + 300);
        timer.restart(time);
    }
    onMounted(() => {
      watchEffect(async () => {
        if(timer.isExpired.value) {
            console.warn('IsExpired')
        }
      })
    })
    return {
        timer,
        restartFive,
     };
  },
});
<template>
  <div>
    <div>
      <span>{{timer.days}}</span>:<span>{{timer.hours}}</span>:<span>{{timer.minutes}}</span>:<span>{{timer.seconds}}</span>
    </div>
    <p>{{timer.isRunning ? 'Running' : 'Not running'}}</p>
    <button @click="timer.start()">Start</button>
    <button @click="timer.pause()">Pause</button>
    <button @click="timer.resume()">Resume</button>
    <button @click="restartFive()">Restart</button>
  </div>
</template>

2. 使用useStopwatch钩子创建一个秒表。

import { defineComponent } from "vue";
import { useStopwatch } from 'vue-timer-hook';
export default defineComponent({
  name: "Home",
  setup() {
    const autoStart = true;
    const stopwatch = useStopwatch(autoStart);
    return {
        stopwatch,
     };
  },
});
<template>
  <div>
    <div>
      <span>{{stopwatch.days}}</span>:<span>{{stopwatch.hours}}</span>:<span>{{stopwatch.minutes}}</span>:<span>{{stopwatch.seconds}}</span>
    </div>
    <p>{{stopwatch.isRunning ? 'Running' : 'Not running'}}</p>
    <button @click="stopwatch.start()">Start</button>
    <button @click="stopwatch.pause()">Pause</button>
    <button @click="stopwatch.reset()">Reset</button>
  </div>
</template>

3. 使用useTime钩子处理时间状态。

import { defineComponent } from "vue";
import { useTime } from 'vue-timer-hook';
export default defineComponent({
  name: "Home",
  setup() {
    const format = '12-hour'
    const time = useTime(format);
    return {
        time,
     };
  },
});
<template>
  <div>
    <div>
      <span>{{time.hours}}</span>:<span>{{time.minutes}}</span>:<span>{{time.seconds}}</span><span>{{time.ampm}}</span>
    </div>
  </div>
</template>