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中已經存儲了當前頁面的路由
若需要在組件中監測這個vuex變量的變化,只需要這么寫
watch:{
"$store.state.curRoutePath"(newval, olval) {
console.log(newval);
},
}