1、引入Vuex状态管理,并定义全局参数
创建src/vuex文件夹,新建index.js文件
import Vue from 'vue'
import Vuex from 'vuex' //引入状态管理
Vue.use(Vuex);
//注册状态管理全局参数
const index = new Vuex.Store({
state: {
user_id: '',
token: ''
},
mutations: {
addToken(state, token) {
localStorage.setItem('token', token)
state.token = token
},
removeToken(state) {
localStorage.removeItem('token')
state.token = undefined
},
}
})
export default index
2、在main.js文件中注册组件
import store from './vuex'
......
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, //注册组件
components: {App},
template: '<App/>'
})
3、Token保存和页面跳转判断
登录成功保存token代码
that.$store.commit('addToken', res.data.result);
在router/index.js文件中配置需要验证token的页面
path: '/',
name: 'MainPage',
component: MainPage,
meta: {
requireAuth: true, // 添加该字段,表示进入这个路由是需要登录的
},
在main.js文件中添加全局路由钩子
router.beforeEach((to, from, next) => {
store.state.token = localStorage.getItem('token')
// 判断该路由是否需要登录权限
if (to.matched.some(function (item) {
return item.meta.requireAuth
})) {
if (store.state.token != null) {
// 通过vuex state获取当前的token是否存
if (Object.keys(from.query).length === 0) {//判断路由来源是否有query,处理不是目的跳转的情况
next()
} else {
let redirect = from.query.redirect//如果来源路由有query
if (to.path === redirect) {//这行是解决next无限循环的问题
next()
} else {
next({path: redirect})//跳转到目的路由
}
}
// next();
} else {
next({
// 将跳转的路由path作为参数,登录成功后跳转到该路由
path: '/login', query: {redirect: to.fullPath}
})
}
} else {
next();
}
})