vue-js-cookie
安装
npm install js-cookie --save
封装
auth.js
import Cookies from 'js-cookie'
const TokenKey = 'stone-token'
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function removeToken() {
return Cookies.remove(TokenKey)
}
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import {getToken, setToken, removeToken} from '../utils/auth'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
token: getToken(),
},
mutations: {
setToken(state, token) {
setToken(token)
},
removeToken(state) {
state.token = null
removeToken()
},
},
actions: {
},
modules: {
}
})
login.vue
let tokenData = res.data.content
this.$store.commit ('setToken',tokenData)
router.js
请求拦截器拦截token
import { getToken } from '@/unit/auth'
router.beforeEach(async (to, from, next) => {
// 是否有token
const token = getToken();
if (token) {
// 有token
// 有token跳登陆页,就给它到主页
if (to.path === '/login') {
next('/overview?id=全国')
} else {
// 有token跳其他页,放行
next();
}
} else {
// 没有token,去登陆页,放行
if (to.path === '/login') {
next();
} else {
// 没有token,去其他页,强制跳到登陆页登录
next('/login')
}
}
});
或者响应拦截器
ajax.interceptors.response.use(success => {
console.log(success);
if(success.data.statusCode == 1000){
router.replace('/login')
return success
} else if(success.data.statusCode == 1001 || success.data.statusCode == 1002){
ElementUI.Message({
message: '用户校验失败',
type: 'error'
});
return success
} else {
return success
}
}, error => {
return Promise.reject(error)
})