关于vue.js:vuexroutersync实例

3次阅读

共计 2277 个字符,预计需要花费 6 分钟才能阅读完成。

1、装置

npm i vuex-router-sync --save

2、应用

import {sync} from 'vuex-router-sync'
import store from './vuex/store'
import router from './router'

sync(store, router, {moduleName: 'RouteModule'})

const app = new Vue({
  router,
  store,
}).$mount('#app');

打印 store.state 即可看到以后路由状态

3、应用场景

如果您想在一个组件中显示一条音讯,心愿在简直每一个页面上都显示“Have a nice day, Jack”,除了首页,因为首页要显示 ”Welcome back, Jack”.
借助 vuex-router-sync,您能够轻松实现

const Top = {template: '<div>{{message}}</div>',
  computed: {message() {return this.$store.getters.getMessage;}
  },
};
const Bar = {template: '<div>{{message}}</div>',
  computed: {message() {return this.$store.getters.getMessage;}
  }
};

const routes = [{
    path: '/top',
    component: Top,
    name: 'top'
  },
  {
    path: '/bar',
    component: Bar,
    name: 'bar'
  },
];

const router = new VueRouter({routes});

const store = new Vuex.Store({
  state: {
    username: 'Jack',
    phrases: ['Welcome back', 'Have a nice day'],
  },
  getters: {getMessage(state) {
      return state.route.name === 'top' ?
        `${state.phrases[0]}, ${state.username}` :
        `${state.phrases[1]}, ${state.username}`;
    },
  },
});

// sync store and router by using `vuex-router-sync`
sync(store, router);

const app = new Vue({
  router,
  store,
}).$mount('#app');

不然的话,你可能须要在 vue-router 的钩子函数里监听,或在 watch 里 $route,而后批改 store 值来实现。

4、原理

在 70 多行的 vuex-router-sync 源代码里有以下几段代码

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

首先是在咱们的 store 中注册了一个 module, 名字默认为 route:

module 中提供了一个叫 ROUTE_CHANGED 的 mutation 解决办法, 而后还把 router 对象中的 currentRoute 保留在了 state 中, 这也是咱们为什么可能通过 this.$store.state.route 拿到 currentRoute 的起因。

而后就是监听 store 中的 route 对象的变动了, 当 route 发生变化并且以后路由名字不等于须要跳转到路由的时候, 间接通过 router 的 push 办法进行跳转页面:

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

store 的 watch 办法跟 vue 中的 watch 是一个概念, 也就是检测某个属性的变动, 而后回调。

最初通过 router 的全局后置钩子函数监听以后路由对象, 批改 store 中的以后 state(以后路由对象):

// sync store on router navigation
var afterEachUnHook = router.afterEach(function (to, from) {if (isTimeTraveling) {
    isTimeTraveling = false
    return
  }
  currentPath = to.fullPath
  store.commit(moduleName + '/ROUTE_CHANGED', { to: to, from: from})
})

————————————————
版权申明:本文为 CSDN 博主「天空还下着雪」的原创文章,遵循 CC 4.0 BY-SA 版权协定,转载请附上原文出处链接及本申明。
原文链接:https://blog.csdn.net/u010081…

正文完
 0