vue-router拦截

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

主要思路

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

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

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

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

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

路由分发拦截

router.beforeEach((to, from, next)=>{//登陆拦截
  if('/Login/Register'.indexOf(to.path)!==-1 || (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===200 && response.data.code===2){//登陆失效拦截
      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(1 === 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() / 1000));
    const random_str = String(Math.floor(Math.random() * (100000 - 10000 + 1) + 10000));
    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': '213123',
      '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官方文档

原文地址:https://www.cnblogs.com/lurenjia1994/p/10098161.html