useNow.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { dateUtil } from '/@/utils/dateUtil';
  2. import { reactive, toRefs } from 'vue';
  3. import { tryOnMounted, tryOnUnmounted } from '@vueuse/core';
  4. export function useNow(immediate = true) {
  5. let timer: IntervalHandle;
  6. const state = reactive({
  7. year: 0,
  8. month: 0,
  9. week: '',
  10. day: 0,
  11. hour: '',
  12. minute: '',
  13. second: 0,
  14. meridiem: '',
  15. });
  16. const update = () => {
  17. const now = dateUtil();
  18. const h = now.format('HH');
  19. const m = now.format('mm');
  20. const s = now.get('s');
  21. state.year = now.get('y');
  22. state.month = now.get('M') + 1;
  23. state.week = '星期' + ['日', '一', '二', '三', '四', '五', '六'][now.day()];
  24. state.day = now.get('date');
  25. state.hour = h;
  26. state.minute = m;
  27. state.second = s;
  28. state.meridiem = now.format('A');
  29. };
  30. function start() {
  31. update();
  32. clearInterval(timer);
  33. timer = setInterval(() => update(), 1000);
  34. }
  35. function stop() {
  36. clearInterval(timer);
  37. }
  38. tryOnMounted(() => {
  39. immediate && start();
  40. });
  41. tryOnUnmounted(() => {
  42. stop();
  43. });
  44. return {
  45. ...toRefs(state),
  46. start,
  47. stop,
  48. };
  49. }