vue 全局路由导航和登录设计

设置 router/index.js

router.beforeEach((to, from, next) => {
  if (to.name !== 'login' && !isAuthenticated) next({ name: 'login' })
  else next()
})

  

完整设置index.js

import Vue from 'vue'
import Router from 'vue-router'

// Avoided redundant navigation to current location
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)

const routes= 
            [
            { path: '/', redirect: '/login' }, 
            { path: '/login', component: () => import('@/components/LoginComponent.vue'),name:'login' },
            { path: '/home', component: () => import('@/components/Home.vue'),name:'home' },
            {path:'*',component:() => import('@/components/404.vue') }
          ]


const router = new Router({
  mode: 'history',
  routes   //   routes:routes
})


// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数

function isAuthenticated(){
  if(localStorage.getItem("token")){
    return true ;
  }else{
    return false;
  }
}

router.beforeEach((to, from, next) => {
  var isauth= isAuthenticated();
  console.log(isauth);
  if (to.name !== 'login' && !isauth) next({ name: 'login' })
  
  else{
    console.log(to.path+"88888");
    next();
  } 
})


export default router

  

登陆js逻辑:

设计思路:

路由名本来是login的路由守卫执行login路由让他取调后台接口,否则就去鉴权通过就路由跳转,不通过直接让他路由到login登录

每次获取token,如果token有则,执行路由login,如果没有直接提示token过期

如果有token,执行路由跳转,

根据res接口后台返回状态码判断如果200,执行跳转

如果非200,根据具体code值执行提示用户名密码错误或者token过期,我这里统一处理成了用户密码错误,实际根据403,401提示

  export default {
    beforeCreate() {
      this.form = this.$form.createForm(this, { name: 'normal_login' });
    },
    methods: {
      // submit method 
      handleSubmit(e) {
        e.preventDefault();
        // var formvalue=document.loginform;
        // console.log(formvalue.userName.value+"
"+formvalue.password.value)
        this.form.validateFields((err, values) => {
          if (!err) {
            let data={
              name:values.userName,
              price:values.password,
              publish:1
            };

            console.log("xxxxxxxxxx",data);
            this.$axios(
              
                {
                    url: '/demo-service/api/v1/book/',
                    method: 'post',
                    data: data,
                    headers:{'Content-Type': 'application/json;charset=UTF-8'},
                    // transformRequest: function (data) {
                    //   // 对 data 进行任意转换处理
                    //   return JSON.stringify(data);
                    // }
                }

              // this.qs.stringify(data)
              ).then(res => {
                // console.log(res);
                if(res.data.code==200){
                  this.$message('真牛逼,已经登陆成功了');
                  // console.log(this.$route);
                  this.$router.push({path:'home'})
                }else{
                  this.$message.error("登陆失败,用户名or密码错误")
                }
                }
              )
              .catch(
              error=> {
                console.log(error);
                this.$message.error("token失效,请重新登陆")
              }
              )
          }
        });
      },
    },
  };

  

原文地址:https://www.cnblogs.com/SunshineKimi/p/14705654.html