1)路由保卫
原理:在router目录下的index.js文件中,使用router的beforeEach方法,判断要跳转的地址,是否是需要授权的,如果需要,判断是否已授权(或已登录),有就跳转,没有,就跳转到登录页面
import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login'
import home from '../views/Home'
Vue.use(VueRouter)
const routes = [{
path: '/',
redirect: '/login'
},
{
path: '/login',
name: 'Login',
component: login
component: () => import('../views/login.vue')
},
{
path: '/home',
name: 'home',
component: home,
redirect: '/welcome', // 重定向
children: [{
path: '/welcome',
component: welcome
}
]
}
]
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => { // to要跳转页面,from原页面,next跳转
if (to.path === '/login') return next();
const tokenst = window.sessionStorage.getItem('token')
if (!tokenst) return next('/login')
next();
})
export default router
2)axios 绑定原生属性
原理:在main.js中对axios进行一下绑定,在后续请求数据时可直接使用
this.$http.get(’ ',params:{ }),get可替换成其他的post / delete 等请求方式
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
axios.interceptors.request.use(config => {
console.log(config)
// 在请求头中使用 `Authorization` 字段提供 `token` 令牌
config.headers.Authorization = window.sessionStorage.getItem('token')
return config
})
Vue.prototype.$http = axios