【Vue实战】简单的登录拦截实现

一、实现目标
    1.引言
      作为一个刚做入门Vue的一个新手,可能会存在这样的疑惑,我是不是可以直接输入URL进行访问,那登录就没有意义了啊。为了解决这个问题,就得使用登录拦截器来实现。关于登录拦截,前后端都可以做,这里我简单介绍一下Vue前端的登录拦截。
    2.需求分析

    当输入访问非登录界面时,进行拦截分析,若有存储账号即可访问,未存储又不是登录界面就进行拦截并跳转登录界面。

二、具体实现
    1.准备工作
    (1)router(重点beforeEach)和Vue的搭建
    (2)LocalStorge的了解参考文章

    2.关键代码

login组件在登录成功使用LocalStorage存储

 this.$axios.post('/adminLogin',params
       ).then( (response)=>{  //注意使用箭头函数
            // handle success
       // this.responseResult=JSON.stringify(response);
       // if(response.status)
           if(response.status==200){
             if(response.data==true){
               console.log(response);
               console.log(response.data);
               localStorage.setItem("userName",this.username);
               this.$notify({
                 title:'成功',
                 message:'登录成功',
                 type:'success'
               })
               // alert(response.data);
               // this.check=response.data;
               this.$router.push({path:'/home'});
             }else {
               alert("密码错误,请重新输入");
             }
           }else{
             console.log('失败');
             alert("连接服务器失败")
           }

          })
          .catch(function (error) {
            // handle error
            console.log(error);
            alert("连接服务器失败")
          })
      },

store的index.js文件加入meta:{requireAuth:{true}}

 {
      path: '/healthWarning',
      name: 'healthWarning',
      component:healthWarning,
      meta:{requireAuth: true}
    },

main.js中进行beforeEach的使用

router.beforeEach((to, from, next) => {

      if(to.name !==" /" && localStorage.getItem("userName")==null){

        alert("请先登录")

        this.$router.push({path:'/'})

      }else next();

    })
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值