记录 关于router路由保卫、axios绑定原生属性的一些知识点

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值