vben
2020-12-09 4ce1d526c80cd859c815b9e629ae1838f441cf0b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import moment from 'moment';
import { reactive, toRefs } from 'vue';
import { tryOnMounted, tryOnUnmounted } from '/@/utils/helper/vueHelper';
import { useLocaleSetting } from '/@/hooks/setting/useLocaleSetting';
 
export function useNow(immediate = true) {
  const { getLang } = useLocaleSetting();
  const localData = moment.localeData(getLang.value);
  let timer: IntervalHandle;
 
  const state = reactive({
    year: 0,
    month: 0,
    week: '',
    day: 0,
    hour: '',
    minute: '',
    second: 0,
    meridiem: '',
  });
 
  const update = () => {
    const now = moment();
 
    const h = now.format('HH');
    const m = now.format('mm');
    const s = now.get('s');
 
    state.year = now.get('y');
    state.month = now.get('M');
    state.week = localData.weekdays()[now.day()];
    state.day = now.get('D');
    state.hour = h;
    state.minute = m;
    state.second = s;
 
    state.meridiem = localData.meridiem(Number(h), Number(h), true);
  };
 
  function start() {
    update();
    clearInterval(timer);
    timer = setInterval(() => update(), 1000);
  }
 
  function stop() {
    clearInterval(timer);
  }
 
  tryOnMounted(() => {
    immediate && start();
  });
 
  tryOnUnmounted(() => {
    stop();
  });
 
  return {
    ...toRefs(state),
    start,
    stop,
  };
}