forked from vuejs/vuex-router-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (66 loc) · 1.7 KB
/
index.js
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
exports.sync = function (store, router, options) {
var moduleName = (options || {}).moduleName || 'route'
store.registerModule(moduleName, {
namespaced: true,
state: cloneRoute(router.currentRoute),
mutations: {
'ROUTE_CHANGED': function (state, transition) {
store.state[moduleName] = cloneRoute(transition.to, transition.from)
}
}
})
var isTimeTraveling = false
var currentPath
// sync router on store change
const storeUnwatch = store.watch(
function (state) { return state[moduleName] },
function (route) {
if (route.fullPath === currentPath) {
return
}
isTimeTraveling = true
var methodToUse = currentPath == null
? 'replace'
: 'push'
currentPath = route.fullPath
router[methodToUse](route)
},
{ sync: true }
)
// sync store on router navigation
const afterEachUnHook = router.afterEach(function (to, from) {
if (isTimeTraveling) {
isTimeTraveling = false
return
}
currentPath = to.fullPath
store.commit(moduleName + '/ROUTE_CHANGED', { to: to, from: from })
})
return function unsync() {
// 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, from) {
var clone = {
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)
}