关于vue-router:vuexroutersync如何使用

简略来讲vuex-router-sync插件就是将vue-router的状态同步到vuex

一、装置

  • npm下载地址:https://www.npmjs.com/package…
> npm i vuex-router-sync --save

二、应用

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即可看到以后路由状态

三、应用场景

如果您想在一个组件中显示一条音讯,心愿在简直每一个页面上都显示“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值来实现。

四、原理

在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_CHANGEDmutation解决办法,而后还把router对象中的currentRoute保留在了state中,这也是咱们为什么可能通过this.$store.state.route拿到currentRoute的起因。

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

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

storewatch办法跟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 })
})

欢送关注:https://www.fenxianglu.cn/

参考链接:

  • https://segmentfault.com/a/11…
  • https://blog.csdn.net/vv_bug/…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理