UNPKG

1.23 kBJavaScriptView Raw
1exports.sync = function (store, router, options) {
2 var moduleName = (options || {}).moduleName || 'route'
3
4 store.registerModule(moduleName, {
5 state: {},
6 mutations: {
7 'router/ROUTE_CHANGED': function (state, transition) {
8 store.state[moduleName] = cloneRoute(transition.to, transition.from)
9 }
10 }
11 })
12
13 var isTimeTraveling = false
14 var currentPath
15
16 // sync router on store change
17 store.watch(
18 function (state) { return state[moduleName] },
19 function (route) {
20 if (route.fullPath === currentPath) {
21 return
22 }
23 isTimeTraveling = true
24 currentPath = route.fullPath
25 router.push(route)
26 },
27 { sync: true }
28 )
29
30 // sync store on router navigation
31 router.afterEach(function (to, from) {
32 if (isTimeTraveling) {
33 isTimeTraveling = false
34 return
35 }
36 currentPath = to.fullPath
37 store.commit('router/ROUTE_CHANGED', { to: to, from: from })
38 })
39}
40
41function cloneRoute (to, from) {
42 var clone = {
43 name: to.name,
44 path: to.path,
45 hash: to.hash,
46 query: to.query,
47 params: to.params,
48 fullPath: to.fullPath,
49 meta: to.meta
50 }
51 if (from) {
52 clone.from = cloneRoute(from)
53 }
54 return Object.freeze(clone)
55}