index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. exports.sync = function (store, router, options) {
  2. var moduleName = (options || {}).moduleName || 'route'
  3. store.registerModule(moduleName, {
  4. namespaced: true,
  5. state: cloneRoute(router.currentRoute),
  6. mutations: {
  7. 'ROUTE_CHANGED': function ROUTE_CHANGED (state, transition) {
  8. store.state[moduleName] = cloneRoute(transition.to, transition.from)
  9. }
  10. }
  11. })
  12. var isTimeTraveling = false
  13. var currentPath
  14. // sync router on store change
  15. var storeUnwatch = store.watch(
  16. function (state) { return state[moduleName]; },
  17. function (route) {
  18. var fullPath = route.fullPath;
  19. if (fullPath === currentPath) {
  20. return
  21. }
  22. if (currentPath != null) {
  23. isTimeTraveling = true
  24. router.push(route)
  25. }
  26. currentPath = fullPath
  27. },
  28. { sync: true }
  29. )
  30. // sync store on router navigation
  31. var afterEachUnHook = router.afterEach(function (to, from) {
  32. if (isTimeTraveling) {
  33. isTimeTraveling = false
  34. return
  35. }
  36. currentPath = to.fullPath
  37. store.commit(moduleName + '/ROUTE_CHANGED', { to: to, from: from })
  38. })
  39. return function unsync () {
  40. // On unsync, remove router hook
  41. if (afterEachUnHook != null) {
  42. afterEachUnHook()
  43. }
  44. // On unsync, remove store watch
  45. if (storeUnwatch != null) {
  46. storeUnwatch()
  47. }
  48. // On unsync, unregister Module with store
  49. store.unregisterModule(moduleName)
  50. }
  51. }
  52. function cloneRoute (to, from) {
  53. var clone = {
  54. name: to.name,
  55. path: to.path,
  56. hash: to.hash,
  57. query: to.query,
  58. params: to.params,
  59. fullPath: to.fullPath,
  60. meta: to.meta
  61. }
  62. if (from) {
  63. clone.from = cloneRoute(from)
  64. }
  65. return Object.freeze(clone)
  66. }