-
Notifications
You must be signed in to change notification settings - Fork 14
/
useToggle.ts
56 lines (50 loc) · 1.49 KB
/
useToggle.ts
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
import { ref, Ref } from 'vue'
export type ToggleParamType = string | number | boolean | undefined | null
export interface ToggleReturn<T extends ToggleParamType = ToggleParamType> {
state: Ref<T>
toggle: (next?: boolean) => void
setDefault: () => void
setRight: () => void
}
export interface ITwoType<T extends ToggleParamType = ToggleParamType, U extends ToggleParamType = ToggleParamType>
extends Omit<ToggleReturn<T>, 'state' | 'toggle'> {
state: Ref<T | U>
toggle: (next?: T | U) => void
}
export interface IToggle {
(): ToggleReturn<boolean>
<T extends ToggleParamType = ToggleParamType>(defaultValue: T): ToggleReturn<T>
<T extends ToggleParamType = ToggleParamType, U extends ToggleParamType = ToggleParamType>(
defaultValue: T,
resetValue?: U
): ITwoType<T, U>
}
export const useToggle: IToggle = <
T extends ToggleParamType = ToggleParamType,
U extends ToggleParamType = ToggleParamType
>(
defaultValue: T = false as T,
reverseValue?: U
) => {
const state = ref(defaultValue) as Ref<T | U>
const reverseTo = (reverseValue === undefined ? !defaultValue : reverseValue) as T | U
const toggle = (next?: T | U) => {
if (next !== undefined) {
state.value = next
} else {
state.value = state.value === defaultValue ? reverseTo : defaultValue
}
}
const setDefault = () => {
state.value = defaultValue
}
const setRight = () => {
state.value = reverseTo
}
return {
state,
setDefault,
setRight,
toggle
}
}