说明:以下均在main.js中添加。

主要思路

1.在路由分发时,检查本地缓存是否有账号信息,如果没有,跳转登陆页面,传入当前路由

2.在发送请求时,添加账号token

3.在接收请求时,检查响应的数据,核对状态码,如果状态码为登陆失效,则重新跳转登陆,传入当前路由

4.登陆界面登陆,跳转到登陆前的路由

理论上可去掉步骤1,步骤1内容在步骤2进行,但发送请求比路由跳转频繁很多(推测)

路由分发拦截

router.beforeEach((to, from, next)=>{//登陆拦截
if('/Login/Register'.indexOf(to.path)!==- || (getLogin().account && getLogin().password)){
next()
}else{
next({
path: '/Login',
query: { redirect: to.fullPath }//添加当前路由信息
})
}
})

添加token以及响应拦截

Vue.http.interceptors.push((request, next) => {
const token = Utils.getAuthorization()//添加令牌
if(''!==token){
// let loginInfo = Utils.getInfo()
// Utils.store.set('login', loginInfo.login, new Date().getTime()+STORE_AGE) //更新时间
// Utils.store.set('user', loginInfo.user, new Date().getTime()+STORE_AGE)
request.headers.set('Authorization', token)//添加token
} let loadingInstance = Loading.service({//显示请求加载框
lock: true,
text: '拼命加载中...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0)'//最后一位透明度,0为全透明
});
next((response) =>{
loadingInstance.close()//关闭请求加载框
if(response.status=== && response.data.code===){//登陆失效拦截
Utils.goLogin(vue)
}
return response
})
})

登陆入口方法

  function goLogin(_this) {
console.dir(_this.$router)
console.dir(_this.$route)
_this.$router.push({path: '/login', query: {redirect: _this.$route.path}})
}

$router: vue-resource实例

$route: 当前路由对象

登陆界面点击按钮触发方法代码

          login(){
this.Utils.login(this, this.form, this.redirect)
}

登陆提交后台代码

  function login(_this, formData, redirect) {
redirect = redirect==='/ChangePwd'? '/': redirect
_this.$http.post(PreURL+'login', this.buildForm(formData)).then((Response) => {
if( === Response.body.code){
store.set('login', formData, new Date().getTime()+STORE_AGE)
store.set('user', Response.body, new Date().getTime()+STORE_AGE)
_this.$router.push({ path: redirect||'/'})
}else{
mAlert(Response.body.message, _this)
}
})
} function buildForm(formData) {
const account = formData.account;
const password = formData.password;
// const phone_uuid = formData.phone_uuid;
const time_stamp = String(Math.round(new Date().getTime() / ));
const random_str = String(Math.floor(Math.random() * ( - + ) + ));
const sha256 = CryptoJS.algo.SHA256.create();
sha256.update(password);
sha256.update(random_str);
sha256.update(time_stamp);
const encryption_str = sha256.finalize().toString();
return {
'phone_number': account,
'password': password,
'phone_uuid': '',
'time_stamp': time_stamp,
'random_str': random_str,
'encryption_str': encryption_str
};
}

vue对象获取

main.js中挂载到window下,其他页面直接用vue就能取到

/* eslint-disable no-new */
window.vue = new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})

参考

vue-router官方文档

vue-router拦截的更多相关文章

  1. vue router拦截器的简单使用

    之前,为了实现router跳转的每个页面的url上都带上addressCode,然后用了一下router拦截器,很好用,当然也可以专门封装一个方法来实现(跳转的页面上带有addressCode),不过 ...

  2. Vue router拦截 如果用户并未登录直接跳转到登录界面(最简单的cookie演示)

    router.beforeEach(function(to,from,next){ console.log('路由拦截') console.log(to.name) console.log(from. ...

  3. vue 路由拦截、axios请求拦截

    路由拦截 项目中,有些页面需要登录后才能进入,例如,在某页面A,用户在操作前需要先进入登录页(此时需要将上一页的地址(/survey/start)作为query存入login页面的地址中,如: htt ...

  4. Vue 2.0 + Vue Router + Vuex

    用 Vue.js 2.x 与相配套的 Vue Router.Vuex 搭建了一个最基本的后台管理系统的骨架. 当然先要安装 node.js(包括了 npm).vue-cli 项目结构如图所示: ass ...

  5. vue router 只需要这么几步

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  6. Vue.js 2.x笔记:路由Vue Router(6)

    1. Vue Router简介与安装 1.1 Vue Router简介 Vue Router 是 Vue.js 官方的路由管理器.它和 Vue.js 的核心深度集成,构建单页面应用. Vue Rout ...

  7. Vue Router学习笔记

    前端的路由:一个地址对应一个组件 Vue Router中文文档 一.路由基本使用 第1步:导入Vue Router: <script src="https://unpkg.com/vu ...

  8. vue router.push(),router.replace(),router.go()和router.replace后需要返回两次的问题

    转载:https://www.cnblogs.com/lwwen/p/7245083.html https://blog.csdn.net/qq_15385627/article/details/83 ...

  9. vue axios拦截器 + 自编写插件 实现全局 loading 效果;

    项目需求:用自定义的 .gif 图标实现全局 loading 效果:为避免在每个页面手动添加,且简单高效的实现,经查阅资料,最终采用了 vue axios拦截器 + 自编写 loading 插件:下面 ...

  10. 前端MVC Vue2学习总结(八)——Vue Router路由、Vuex状态管理、Element-UI

    一.Vue Router路由 二.Vuex状态管理 三.Element-UI Element-UI是饿了么前端团队推出的一款基于Vue.js 2.0 的桌面端UI框架,手机端有对应框架是 Mint U ...

随机推荐

  1. rsyncd 配置使用

    查询rpm -qa | grep rsync 配置文件需手动创建: touch /etc/rsyncd.conf 配置/etc/rsyncd.conf: (全局配置) uid = root //rsy ...

  2. 【BZOJ3165】[HEOI2013]Segment(李超线段树)

    [BZOJ3165][HEOI2013]Segment(李超线段树) 题面 BZOJ 洛谷 题解 似乎还是模板题QwQ #include<iostream> #include<cst ...

  3. 【AtCoder3611】Tree MST(点分治,最小生成树)

    [AtCoder3611]Tree MST(点分治,最小生成树) 题面 AtCoder 洛谷 给定一棵\(n\)个节点的树,现有有一张完全图,两点\(x,y\)之间的边长为\(w[x]+w[y]+di ...

  4. Speech语音播报

    System.Speech 这个命名空间,报可以阅读文字和播放音频. 环境  W10 VS2017 CMMT 1.添加程序集引用 System.Speech 2.实例化播音类,并且播放一个文本 Spe ...

  5. 洛谷 P1129 [ZJOI2007]矩阵游戏 解题报告

    P1129 [ZJOI2007]矩阵游戏 题目描述 小\(Q\)是一个非常聪明的孩子,除了国际象棋,他还很喜欢玩一个电脑益智游戏――矩阵游戏.矩阵游戏在一个\(N*N\)黑白方阵进行(如同国际象棋一般 ...

  6. HR_Two Strings

    https://www.hackerrank.com/challenges/two-strings/problem?h_l=interview&playlist_slugs%5B%5D=int ...

  7. Ubuntu16.04下的NetCore环境搭建(附录含Ubuntu 18.04 安装 NetCore2.1)

    跨平台系列汇总:http://www.cnblogs.com/dunitian/p/4822808.html#linux VSCode安装:http://www.cnblogs.com/dunitia ...

  8. staitc

    一.static和非static变量 1. static 修饰的变量称为类变量或全局变量或成员变量,在类被加载的时候成员变量即被初始化,与类关联,只要类存在,static变量就存在.非static修饰 ...

  9. Python经典算法片段

    将一个正整数分解质因数 #!/bin/env python2 # -*- coding: UTF-8 -*- def reduceNum(n): print '{} = '.format(n), if ...

  10. bzoj3467: Crash和陶陶的游戏

    就一篇题解: BZOJ3467 : Crash和陶陶的游戏 - weixin_34248487的博客 - CSDN博客 1.离线,建出Atrie树:B树的倍增哈希数组,节点按照到根路径字典序排序 2. ...