安装

npm install vuex-router-sync --save

配置使用

import {sync} from 'vuex-router-sync'

sync(store, router)

通过sync方法把store跟router连接起来,在vue组件中this.$store.state.route,返回结果即router中的currentRoute对象

源码

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
exports.sync = function (store, router, options) {
var moduleName = (options || {}).moduleName || 'route'

// store 中注册一个 module,名称默认‘route’
store.registerModule(moduleName, {
namespaced: true,
state: cloneRoute(router.currentRoute),
mutations: {
'ROUTE_CHANGED': function ROUTE_CHANGED (state, transition) {
store.state[moduleName] = cloneRoute(transition.to, transition.from)
}
}
})

var isTimeTraveling = false
var currentPath

// 监听 store 中 route 对象的变化
var storeUnwatch = store.watch(
function (state) { return state[moduleName]; },
function (route) {
var fullPath = route.fullPath;
if (fullPath === currentPath) {
return
}
if (currentPath != null) {
isTimeTraveling = true
router.push(route)
}
currentPath = fullPath
},
{ sync: true }
)

// 通过router的全局后置钩子函数监听当前路由对象,修改store中的当前state
var 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 () {
if (afterEachUnHook != null) {
afterEachUnHook()
}

if (storeUnwatch != null) {
storeUnwatch()
}

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)
}