forked from vuejs/vuex-router-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (44 loc) · 1.2 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
exports.sync = function (store, router, options) {
var moduleName = (options || {}).moduleName || 'route'
store.registerModule(moduleName, {
state: {},
mutations: {
'router/ROUTE_CHANGED': function (state, transition) {
store.state[moduleName] = Object.freeze({
name: transition.to.name,
path: transition.to.path,
hash: transition.to.hash,
query: transition.to.query,
params: transition.to.params,
fullPath: transition.to.fullPath,
meta: transition.to.meta,
from: transition.from
})
}
}
})
var isTimeTraveling = false
var currentPath
// sync router on store change
store.watch(
function (state) { return state[moduleName] },
function (route) {
if (route.fullPath === currentPath) {
return
}
isTimeTraveling = true
currentPath = route.fullPath
router.push(route)
},
{ sync: true }
)
// sync store on router navigation
router.afterEach(function (to, from) {
if (isTimeTraveling) {
isTimeTraveling = false
return
}
currentPath = to.fullPath
store.commit('router/ROUTE_CHANGED', { to: to, from: from })
})
}