axios http拦截
http.js配置
/** * Created by superman on 17/2/16. * http配置 */import axios from 'axios'import { Loading, Message } from 'element-ui'import store from './store/store.js'import * as types from './store/types.js'import router from './index.js'import config from './config.js'// axios 配置 config.js//axios.defaults.timeout = 5000;//axios.defaults.baseURL = 'https://api.github.com';//axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';// http request 拦截器axios.interceptors.request.use( config => { if ($.cookie("token")) { config.headers._token = $.cookie("token"); } return config; }, err => { return Promise.reject(err); });// http response 拦截器axios.interceptors.response.use( response => { if (response.data.code == 2) { window.location.href = "/#/login"; $.cookie("user", null); $.cookie("token", null); return ""; } else { return response; } }, error => { if (error.response) { switch (error.response.status) { case 401: // 401 清除token信息并跳转到登录页面 store.commit(types.LOGOUT); router.replace({ path: 'login' //query: {redirect: router.currentRoute.fullPath} }) } } // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402 return Promise.reject(error.response.data) });export default axios;
路由的index.js配置
页面刷新时,重新赋值tokenif ($.cookie('token')) { store.commit(types.LOGIN, $.cookie('token'))}
main.js配置
import Vue from 'vue'import axios from './router/http' //引入配置的http文件import vuex_store from './router/store/store'import App from './App'import router from './router/index.js'import VeeValidate from 'vee-validate'import share from '../static/js/jquery.share.min.js'import Vuex from 'vuex';import Paginate from 'vuejs-paginate'
vuex的store.js文件
import Vue from 'vue'import Vuex from 'vuex';import * as types from './types'Vue.use(Vuex);//storeconst vuex_store = new Vuex.Store({ state: { loginShow: false, registerShow: false, forgetPwd: false, surePwd: false, findPwd: false, goRegister: false, //点击注册 goLogin: false, //点击登录 dataRecord: false, goodsRecord: false, //生成企业 && 集团 wxRecord: false, //维修企业 user: {}, token: $.cookie("token"), title: '', zscxVal: "1212", logicTit: "", logicTit2: "", dataInfo: [], saleType: null, logincomponent: false, }, mutations: { [types.LOGIN]: (state, data) => { $.cookie('token', data, { path: '/' }); //localStorage.token = data; state.token = data; }, [types.LOGOUT]: (state) => { //localStorage.removeItem('token'); $.cookie('token', null); state.token = null }, [types.TITLE]: (state, data) => { state.title = data; }, outputType: function(state, obj) { if (obj.num == 1) { state.saleType = "销售出库"; } else { state.saleType = "其他出库"; } } }})export default vuex_store;
type.js是定义常量mutation的名称
/** * Created by superman on 17/2/16. * vuex types */export const LOGIN = 'login';export const LOGOUT = 'logout';export const TITLE = 'title'
路由拦截
首先在定义路由的时候就需要多添加一个自定义字段requireAuth,用于判断该路由的访问是否需要登录。如果用户已经登录,则顺利进入路由, 否则就进入登录页面。
在Vue2.0中的路由钩子主要是用来拦截导航,让它完成跳转或前取消,可以理解为路由守卫。
分为全局导航钩子,单个路由独享的钩子,组件内钩子。 三种 类型的钩子只是用的地方不一样,都接受一个函数作为参数,函数传入三个参数,分别为to,from,next。
其中next有三个方法
(1)next(); //默认路由
(2)next(false); //阻止路由跳转
(3)next({path:’/’}); //阻止默认路由,跳转到指定路径
import Vue from 'vue'import Router from 'vue-router'Vue.use(Router)const router = new Router({ routes: [ { path: '/', /* * 按需加载 */ component: (resolve) => { require(['../components/Home'], resolve) } }, { path: '/record', name: 'record', component: (resolve) => { require(['../components/Record'], resolve) } }, { path: '/Register', name: 'Register', component: (resolve) => { require(['../components/Register'], resolve) } }, { path: '/Luck', name: 'Luck', // 需要登录才能进入的页面可以增加一个meta属性 meta: { requireAuth: true }, component: (resolve) => { require(['../components/luck28/Luck'], resolve) } } ]})// 判断是否需要登录权限 以及是否登录router.beforeEach((to, from, next) => { store.commit('router', to.path.split("/")[1]); if (to.matched.some(res => res.meta.requireAuth)) { // 判断是否需要登录权限 if (localStorage.getItem('ms_username')) {// 判断是否登录 next() } else {// 没登录则跳转到登录界面 next({ path: '/Register' }) } } else { next() }})export default router