首先確保我們已經設置的store.js進行值的存取,這時候我們需要配置請求和響應的攔截器設置
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
// 引入store
import store from './store'
// 如何localStorage的token不存在或是空跳轉到路由
router.beforeEach((to, from, next) => {
if (to.path === '/') {
next();
} else {
let token = window.localStorage.token;
if (token === 'null' || token === '' || token === undefined) {
next('/');
} else {
next();
}
}
})
//與后端定義狀態是100簽名錯誤 跳轉到登錄界面
axios.interceptors.response.use(
response => {
//當返回信息為未登錄或者登錄失效的時候重定向為登錄頁面
if (response.data.status == 100 || response.data.message == '用戶未登錄或登錄超時,請登錄!') {
router.push({
path: "/",
querry: { redirect: router.currentRoute.fullPath }//從哪個頁面跳轉
})
}
return response;
},
error => {
return Promise.reject(error)
}
)
