在vue2.0中的路由钩子主要是用来拦截导航,让它完成跳转或前取消,可以理解为路由守卫。
分为全局导航钩子,单个路由独享的钩子,组件内钩子。
三种 类型的钩子只是用的地方不一样,都接受一个函数作为参数,函数传入三个参数,分别为to,from,next。
其中next有三个方法
(1)next(); //默认路由
(2)next(false); //阻止路由跳转
(3)next({path:'/'}); //阻止默认路由,跳转到指定路径
这里我使用了组件内钩子进行判断token过期后跳转到登录页,其他两种钩子可以去官网查看。
- //路由前验证
- beforeRouteEnter(to, from, next) {
- let postdata = {
- meta: {
- client_version: "1.0",
- client_type: "1",
- },
- data: {
- access_token: $.cookie("authtoken").toString()
- }
- }
- $.ajax({
- url: urls.serchuser,
- type: 'POST',
- data: JSON.stringify(postdata)
- }).done(data = >{
- data = JSON.parse(data);
- console.log(data);
- if (data.status == 10050) {
- next(false);
- location.href = 'login.html';
- } else {
- next();
- }
- })
- }
实现方法很简单,在路由前向服务器发送请求,如果返回的数据表明token过期则阻止默认跳转,否则就正常跳转。
以上这篇Vue利用路由钩子token过期后跳转到登录页的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持就爱阅读。
来源: http://www.92to.com/bangong/2017/10-26/30445269.html