-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathindex.ts
103 lines (89 loc) · 2.19 KB
/
index.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { Store } from 'vuex'
import VueRouter, { Route } from 'vue-router'
export interface SyncOptions {
moduleName: string
}
export interface State {
name?: string | null
path: string
hash: string
query: Record<string, string | (string | null)[]>
params: Record<string, string>
fullPath: string
meta?: any
from?: Omit<State, 'from'>
}
export interface Transition {
to: Route
from: Route
}
export function sync(
store: Store<any>,
router: VueRouter,
options?: SyncOptions
): () => void {
const moduleName = (options || {}).moduleName || 'route'
store.registerModule(moduleName, {
namespaced: true,
state: cloneRoute(router.currentRoute),
mutations: {
ROUTE_CHANGED(_state: State, transition: Transition): void {
store.state[moduleName] = cloneRoute(transition.to, transition.from)
}
}
})
let isTimeTraveling: boolean = false
let currentPath: string
// sync router on store change
const storeUnwatch = store.watch(
(state) => state[moduleName],
(route: Route) => {
const { fullPath } = route
if (fullPath === currentPath) {
return
}
if (currentPath != null) {
isTimeTraveling = true
router.push(route as any)
}
currentPath = fullPath
},
{ sync: true } as any
)
// sync store on router navigation
const afterEachUnHook = router.afterEach((to, from) => {
if (isTimeTraveling) {
isTimeTraveling = false
return
}
currentPath = to.fullPath
store.commit(moduleName + '/ROUTE_CHANGED', { to, from })
})
return function unsync(): void {
// On unsync, remove router hook
if (afterEachUnHook != null) {
afterEachUnHook()
}
// On unsync, remove store watch
if (storeUnwatch != null) {
storeUnwatch()
}
// On unsync, unregister Module with store
store.unregisterModule(moduleName)
}
}
function cloneRoute(to: Route, from?: Route): State {
const clone: State = {
name: to.name,
path: to.path,
hash: to.hash,
query: to.query,
params: to.params,
fullPath: to.fullPath,
meta: to.meta
}
if (from) {
clone.from = cloneRoute(from)
}
return Object.freeze(clone)
}