vuex-router-sync如何使用

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

一、安装

  • npm下载地址:https://www.npmjs.com/package/vuex-router-sync
> 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即可看到当前路由状态

image

三、使用场景

假如您想在一个组件中显示一条消息,希望在几乎每一个页面上都显示“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/1190000019925019
  • https://blog.csdn.net/vv_bug/article/details/84064708
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天空还下着雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值