提交 | 用户 | 时间
|
314507
|
1 |
import { dateUtil } from '@/utils/dateUtil' |
H |
2 |
import { reactive, toRefs } from 'vue' |
|
3 |
import { tryOnMounted, tryOnUnmounted } from '@vueuse/core' |
|
4 |
|
|
5 |
export const useNow = (immediate = true) => { |
|
6 |
let timer: IntervalHandle |
|
7 |
|
|
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 |
|
|
19 |
const update = () => { |
|
20 |
const now = dateUtil() |
|
21 |
|
|
22 |
const h = now.format('HH') |
|
23 |
const m = now.format('mm') |
|
24 |
const s = now.get('s') |
|
25 |
|
|
26 |
state.year = now.get('y') |
|
27 |
state.month = now.get('M') + 1 |
|
28 |
state.week = '星期' + ['日', '一', '二', '三', '四', '五', '六'][now.day()] |
|
29 |
state.day = now.get('date') |
|
30 |
state.hour = h |
|
31 |
state.minute = m |
|
32 |
state.second = s |
|
33 |
|
|
34 |
state.meridiem = now.format('A') |
|
35 |
} |
|
36 |
|
|
37 |
function start() { |
|
38 |
update() |
|
39 |
clearInterval(timer) |
|
40 |
timer = setInterval(() => update(), 1000) |
|
41 |
} |
|
42 |
|
|
43 |
function stop() { |
|
44 |
clearInterval(timer) |
|
45 |
} |
|
46 |
|
|
47 |
tryOnMounted(() => { |
|
48 |
immediate && start() |
|
49 |
}) |
|
50 |
|
|
51 |
tryOnUnmounted(() => { |
|
52 |
stop() |
|
53 |
}) |
|
54 |
|
|
55 |
return { |
|
56 |
...toRefs(state), |
|
57 |
start, |
|
58 |
stop |
|
59 |
} |
|
60 |
} |