美文网首页
vue登录验证 demo

vue登录验证 demo

作者: 缪先生_ | 来源:发表于2020-10-16 11:06 被阅读0次

    axios.js (捕获token自然过期)

    import axios from "axios";
    import store from "@/store/index";
    import router from '@/router'
    import { Message } from 'element-ui';
    axios.interceptors.response.use((response)=> {
        if (response.data.code == 403) {
           store.dispatch('loginChange',false).then(()=>{
            // console.log(router.currentRoute);
            let {msg="未登录或登录失效"} = response.data;
            if(router.currentRoute.path!='/login'&&router.currentRoute.path!='/'){
              Message.warning(msg);
              router.replace({
                path: '/login',
                query: {
                  redirect: router.currentRoute.fullPath,//重定向地址
                }
              });
            }
          })
        } else {
          return response.data;
        }
      }
    );
    
    

    router.js (捕获地址栏跳转)

    import Vue from 'vue';
    import Router from 'vue-router';
    import store from "@/store/index.js"
    import { URLS } from "@/config/api";
    let v = new Vue();
    router.beforeEach((to, from, next) => {
      //验证用户是否登录,如未登录,跳到登录,反之。
      if (!store.state.isLoginType) {
        //登录 验证
        v.axios.get(URLS.departmentDownList).then(res => {
            if (res && res.success) {
                //验证成功
                store.dispatch('loginChange', true).then(() => {
                    //登录状态下,不可以跳转到登录界面 =>重定向
                    to.path === '/login' ? next({ path: '/blueprint', replace: true }) : next();
                })
            } else {
                //验证失败
                //重定向登录 跳出循环
                to.path === '/login' ? next() : store.dispatch('loginChange', false).then(() => next({ path: '/login', replace: true }));
            }
        }).catch(err => {
            //验证失败
            to.path === '/login' ? next() : store.dispatch('loginChange', false).then(() => next({ path: '/login', replace: true }));
        })
      } else {
        //登录
        to.path === '/login' ? next({ path: from.path, replace: true }) : next();
      }
    });
    

    store/index.js vuex

    import Vuex from 'vuex'
    Vue.use(Vuex)
    export default new Vuex.Store({
      state: {
        isLoginType:false,//用户是否登录
      },
      mutations: {
        /*
        * 更改用户登陆状态
        */
        loginChange(state, res) {
          if (res) {
            state.isLoginType = true;
          } else {
            state.isLoginType = false;
          }
        },
      },
      actions:{
        /*
        * 更改用户登陆状态
        */
        loginChange({commit},res) {
          commit('loginChange', res);
        },
      },
    })
    

    相关文章

      网友评论

          本文标题:vue登录验证 demo

          本文链接:https://www.haomeiwen.com/subject/dnhzpktx.html