UNPKG

1.59 kBJavaScriptView Raw
1exports.sync = function (store, router) {
2 patchStore(store)
3 store.router = router
4
5 var commit = store.commit || store.dispatch
6 var isTimeTraveling = false
7 var currentPath
8
9 // sync router on store change
10 store.watch(
11 function (state) {
12 return state.route
13 },
14 function (route) {
15 if (route.path === currentPath) {
16 return
17 }
18 isTimeTraveling = true
19 currentPath = route.path
20 router.go(route.path)
21 },
22 { deep: true, sync: true }
23 )
24
25 // sync store on router navigation
26 router.afterEach(function (transition) {
27 if (isTimeTraveling) {
28 isTimeTraveling = false
29 return
30 }
31 var to = transition.to
32 currentPath = to.path
33 commit('router/ROUTE_CHANGED', to)
34 })
35}
36
37function applyMutationState(store, state) {
38 // support above 2.0
39 if (store.hasOwnProperty('_committing')) {
40 return store._committing = state
41 }
42 return store._dispatching = state
43}
44
45function patchStore (store) {
46 // add state
47 var set = store._vm.constructor.set
48 applyMutationState(store, true);
49 set(store.state, 'route', {
50 path: '',
51 query: null,
52 params: null
53 })
54 applyMutationState(store, false);
55
56 var routeModule = {
57 mutations: {
58 'router/ROUTE_CHANGED': function (state, to) {
59 store.state.route = to
60 }
61 }
62 }
63
64 // add module
65 if (store.registerModule) {
66 store.registerModule('route', routeModule)
67 } else if (store.module) {
68 store.module('route', routeModule)
69 } else {
70 store.hotUpdate({
71 modules: {
72 route: routeModule
73 }
74 })
75 }
76}