useNow.ts 1.2 KB

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