Loading

VueX和Vue-Router路由结合使用

Vuex和Vue-router路由结合使用

版本环境:"vuex": "^3.4.0", "vue": "^2.6.11","vue-router": "^3.2.0",

例如现在我想在我每次修改路由地址的时候将这个地址存入vuex,进行动态管理,观察改动等等

参考了 https://forum.quasar-framework.org/topic/4160/solved-access-vuex-store-in-router-js

首先在 vuex中写入需要的 state、mutations、actions等子模块

import Vuex from 'vuex';
Vue.use(Vuex)
export default new Vuex.Store({
  state:{
    curRoutePath: '', //当前路由地址
  },
  mutations:{
     	CHANGE_CUR_ROUTE_PATH(state, payload) { //同步存储
			state.curRoutePath = payload
		}, 
  },
  actions:{
      changeCurRoutePath({commit},payload{ //异步存储
         commit('CHANGE_CUR_ROUTE_PATH', payload) 
      })
  }
})

然后找到路由vue-router的主文件index.js (通常在@/route/index.js中)

当我们检测到本地存有token,用户拥有当前页面的权限时,通常可以正常跳转,而这时候可以把要成功跳转的路由地址存入vuex中了。

import store from '@/store/index'; //直接导入store对象
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
	mode: 'hash',
	routes
})
router.beforeEach((to, from, next) => {
	//路由拦截
	if (to.path === '/') {
		return next();
	}
	const token = window.localStorage.getItem('token')
	if (!token) {
		return next('/')
	}
	let routerList = window.localStorage.getItem('routerList')

	if (!routerList) {
		return next('/')
	} else {
		routerList = JSON.parse(routerList)
		let routerArr = TreeConvertList(routerList)
		if (routerArr.indexOf(to.path) > -1) {
            //成功的跳转 存入vuex
			store.commit('CHANGE_CUR_ROUTE_PATH', to.path)
			return next()
		} else {
			return next(false)
		}
	}
})
export default router

打开vue tools调试工具,可以看到vuex中已经存储了当前页面的路由

image-20220111163746685

若需要在组件中监测这个vuex变量的变化,只需要这么写

watch:{
    "$store.state.curRoutePath"(newval, olval) {
      console.log(newval);
    },
} 
posted @ 2022-01-11 21:39  Maji-May  阅读(1617)  评论(0编辑  收藏  举报