vue登录页面cookie的使用及页面跳转

1、大概流程

 a、登录:前端使用validate对输入信息进行验证 验证成功则成功跳转到用户信息页并存储cookie值

 b、首页跳转用户信息页:判断cookie值cookie存在并不为空则跳转用户信息页,若为空则跳转登录页

 c、退出页:点击退出跳转首页并删除cookie值

2、目录介绍

cookie.js为公共方法,用于cookie的存储、获取及删除

login.vue :登录页

index.vue:首页

user.vue:用户信息页

myinfo.vue:退出页


3、文件内容

a、cookie.js

/*用export把方法暴露出来*/
/*设置cookie*/
export function setCookie(c_name,value,expire) {
    var date=new Date()
    date.setSeconds(date.getSeconds()+expire)
    document.cookie=c_name+ "="+escape(value)+"; expires="+date.toGMTString()
    //console.log(document.cookie)
}


/*获取cookie*/
export function getCookie(c_name){
    if (document.cookie.length>0){
        let c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1){ 
            c_start=c_start + c_name.length+1 
            let c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
                return unescape(document.cookie.substring(c_start,c_end))
            } 
        }
    return ""
}


/*删除cookie*/
export function delCookie(c_name){
    setCookie(c_name, "", -1)
}

b、login.vue

methods:{

  submit(){

              setCookie('username',username,1000*60)
      axios.get('http://172.16.2.43:8080/static/data/mt_index.json').then((res)=>{
this.$router.push({
                  path: '/user', query:{userid: $("input[name='username']").val()}
                 });  
                 //this.setuserid($("input[name='username']").val());               
}) 

  }

}

c、index.vue

<div class="topheader">
    <span class="location fl">北京</span>
    <div class="search-box">
         <a href=""><input type="text"></a>            
    </div>
    <span class="mine" @click="jampmin">我的</span>
</div>
jampmin(){
    //获取cookie值
    var username=getCookie('username');
    if(username==''||username=='undefind'){
      this.$router.push({
               path: '/login'
           });
    }else{
      this.$router.push({
               path: '/user'
           });
    }         

d、myinfo.vue

 <p @click="signout()" class="signout">退出</p>

signout(){
   /*删除cookie*/
   delCookie('username');
   this.$router.push({
       path: '/index'
    });

}


写项目时参考的文档https://segmentfault.com/a/1190000009329619 写的很清楚

猜你喜欢

转载自blog.csdn.net/lsy__lsy/article/details/80239526
今日推荐