1.路由拦截器router.beforeEach 运行在vue路由切换的时候
router.afterEacher
beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave
router.beforeEach((to,from,next)=>{
if(to.path=='/login' || localStorage.getItem('token')){
next();
}else{
alert('请重新登录');
next('/login');
}
})
2.请求拦截器Vue.http.interceptors 运行在你http请求的时候
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>Document</title>
</head>
<body>
<a href="http://www.baidu.com"></a>
<script>
ah.proxy({
onRequest: (config, handler) => {
config.headers[ 'aaaaaaaaaatoken' ] = 'dhk'
// if (config.url === 'https://aa/' || config.url === 'https://bb/') {
// console.log('aaa.com')
// handler.resolve({
// config: config,
// status: 200,
// headers: {'content-type': 'text/text'},
// response: 'aa hi world'
// })
// } else {
// handler.next(config);
// }
handler.next(config);
},
onError: (err, handler) => {
if (err.config.url === 'https://bb/') {
handler.resolve({
config: err.config,
status: 200,
headers: {'content-type': 'text/text'},
response: 'bb hi world'
})
} else {
handler.next(err)
}
handler.next(err)
},
onResponse: (response, handler) => {
if (response.config.url === location.href) {
handler.reject({
config: response.config,
type: 'error'
})
} else {
handler.next(response)
}
}
})
// 使用jQuery发起网络请求
// function testJquery(url) {
// $.get(url).done(function (d) {
// console.log('success:' ,d)
// }).fail(function (e) {
// console.log('fail')
// })
// }
// //测试
// testJquery('https://aa/');
// // testJquery('https://suggest.taobao.com/');
// testJquery('https://bb/');
// testJquery(location.href)
// axios请求
// axios.post('/user', {
// firstName: 'Fred',
// lastName: 'Flintstone'
// })
// .then(function (response) {
// console.log(response);
// })
// .catch(function (error) {
// console.log(error);
// });
// axios请求多个
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.post('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
</script>l
</body>
</html>
点击相同路由菜单,报错,可以加这段
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
return originalReplace.call(this, location).catch(err => err);
};