1 | exports.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 |
|
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 |
|
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 |
|
37 | function applyMutationState(store, state) {
|
38 |
|
39 | if (store.hasOwnProperty('_committing')) {
|
40 | return store._committing = state
|
41 | }
|
42 | return store._dispatching = state
|
43 | }
|
44 |
|
45 | function patchStore (store) {
|
46 |
|
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 |
|
65 | if (store.module) {
|
66 | store.module('route', routeModule)
|
67 | } else {
|
68 | store.hotUpdate({
|
69 | modules: {
|
70 | route: routeModule
|
71 | }
|
72 | })
|
73 | }
|
74 | }
|