用vue实现注册页面、登录页面、主页之间跳转并保持登录状态【完整代码】

39 篇文章 1 订阅
本文介绍了如何使用Vue.js实现登录、注册和主页间的页面跳转,并利用localStorage保持登录状态。用户登录后,关闭浏览器再打开时,根据localStorage的状态决定是否直接显示主页。同时详细展示了登录、注册和主页的页面布局代码,以及路由配置和全局守卫的使用,确保用户在保持登录的情况下能够无缝浏览。
摘要由CSDN通过智能技术生成

文章目录


前言

本文主要讲解用vue来实现三个页面之间的跳转以及登录状态的实现,css还在努力学习中,所以界面做的很丑lol

要求:

1.三个页面,登录页面Login,注册页面Register,主页Home
2.用route路由实现不同页面逻辑跳转
3.登录状态

  1. 打开网页时,不论输入的路由是什么,先判断是否已是登录状态,如果用户为登录状态,则直接显示主页;否则强制显示登录页
  2. 如果用户未选保持登录状态,则要在关闭浏览器后,再重新访问页面时,为未登录状态
  3. 如果用户选择了保持登录状态,则在关闭浏览器后,再重新访问页面时,为已登录状态
  4. 退出登录后,更改状态为不保持登录状态

一、页面的简单实现

1.登录页面

在这里插入图片描述

代码实现

<template>
<div id="background">
    <div class="container">
        <form action="">
          <h1>Login</h1>
          <div class="form">
              <div class="item">
                <label>用户名:</label><input type="text" name="username" v-model.trim="name" placeholder="请输入用户名">
                <!-- v-model把输入的值传输给name变量 -->
                <br/>
              </div>
              <div class="item">
                <label>密码:</label><input type="password" name="password" v-model.trim="password" placeholder="请输入密码">
                <br/>
              </div>
              <div class="keep">
                <input @click="handlesave" id="yes" type="radio" value="0" ><!-- 点击选中 -->
                <label for="yes">保持登录状态</label>
              </div>
          </div>
          
        </form>
              <button  type="submit" @click.prevent="handlelogin">登录			</button>
              <!-- v-on点击按钮触发handlelogin方法 -->
              <button  @click.prevent="handleregister">注册</button>
          <router-view></router-view>
    </div>
</div>
</template>
//css
<style scoped>
#background{
    width: 100%;
    height: 100%;
    background: url("../assets/bg2.jpg");
    background-size:100% 100%;
    position: fixed;
    top: 0;
    left: 0;
}

.container{
  width: 480px;
  height: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background:#00000090;
  text-align: center;
  border-radius: 20px;
  margin-top: 10px;
}
.container h1{
  color: aliceblue;
  margin-left: 20px;
}
.item {
  color: white;
  margin-left: 15%;
  margin-top: 35px;
  font-size: 20px;
  text-align: left;
}
.item label{
  float:left;
  width: 5em;
  margin-right: 1em;
  text-align: right;
}
input{
  margin-left: -5px;
  padding: 4px;
  border: solid 1px #4e5ef3;
  outline: 0;
  font: normal 13px/100% Verdana,Tahoma,sans-serif;
  width: 200px;
  height: 23px;
  background:#f1f1f190;
  box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}
button{
  position: relative;
  height: 33px;
  width: 100px;
  background: rgba(35, 19, 252, 0.425);
  border-radius: 10px;
  margin-top: 18px;
  box-shadow: none;
  color: white;
  margin-left: 40px;
  margin-right: 10px;

}
.keep{
  color: white;
}
.keep input{
  width: 15px;
  height: 15px;
  margin-top: 7px;
  margin-left: 10px;
  margin-right: 10px;
}

</style>

2.注册页面

在这里插入图片描述
代码实现

<template>
    <div id="background">
      <div id="contain">
        <h1>Register</h1>

        <div class="form">
          <label>用户名:</label><input type="text" v-model.trim="name"><br/>
        </div>
        <div class="form">
          <label>密码:</label><input type="password" v-model.trim="password"><br/>
        </div>
        <div class="form">
          <label>邮箱:</label><input type="email" v-model.trim="mail"><br/>
        </div>
        <div class="form">
          <label>手机号:</label><input type="tel" v-model.trim="tel"><br/>
        </div>
        <button @click.prevent="handlefinish">提交</button>
      </div>
    </div>
</template>
//css
<style scoped>
#background{
  width: 100%;
    height: 100%;
    background: url("../assets/bg2.jpg");
    background-size:100% 100%;
    position: fixed;
    top: 0;
    left: 0;
}
#contain{
  width: 580px;
  height: 560px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background:#00000090;
  text-align: center;
  border-radius: 20px;
}
#contain h1{
  color: white;
}
.form{
  color: white;
  margin-left: 20%;
  margin-top: 60px;
  font-size: 20px;
  text-align: left;
}
label{
  float:left;
  width: 5em;
  margin-right: 1em;
  text-align: right;
}
input,textarea{
  margin-left: 10px;
  padding: 4px;
  border: solid 1px #4e5ef3;
  outline: 0;
  font: normal 13px/100% Verdana,Tahoma,sans-serif;
  width: 200px;
  height: 20px;
  background:#f1f1f190;
  box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}
input:hover,textarea:hover,input:focus,textarea:focus{border-color:#0d0aa1;}
button{
  position: relative;
  height: 33px;
  width: 150px;
  background: rgba(35, 19, 252, 0.425);
  border-radius: 10px;
  margin-top: 38px;
  box-shadow: none;
  color: white;
  margin-left: 40px;
}
</style>

3.主页(显示个人信息)

在这里插入图片描述
代码实现

<template>
    <div id="bg">
      <div id="container">
        <h1>个人信息</h1>
      <p><span>姓名:</span>{{sname}}</p>
      <p><span>邮箱:</span>{{smail}}</p>
      <p><span>手机号:</span>{{stel}}</p>
      <button @click.prevent="logout">退出</button>
      </div>
    </div>
</template>
//css
<style scoped>
#container{
  width: 480px;
  height: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background:#00000090;
  text-align: center;
  border-radius: 20px;
  margin-top: 10px;
  color: white;
}
#bg{
  width: 100%;
    height: 100%;
    background: url("../assets/bg2.jpg");
    background-size:100% 100%;
    position: fixed;
    top: 0;
    left: 0;
}
p{
  font-size: 20px;
  margin-top: 20px;
  text-align: left;
  margin-left: 32%;
  
}
button{
  position: relative;
  height: 33px;
  width: 150px;
  background: rgba(35, 19, 252, 0.425);
  border-radius: 10px;
  margin-top: 10px;
  box-shadow: none;
  color: white;
  margin-left: 10px;
}

二、逻辑实现

说明:这里存储数据用的是localStorage

1.localStorage的使用

localStorage.setItem(string key,string value) 将键值对添加到存储中
localStorage.getItem(string key) 获取对应的键值

2.功能实现

登录

<script>
export default {
  data(){
    return{
      name:"",//姓名,用v-model绑定监听,将输入的字符串赋值给name变量
      password:"",//密码
      st:"false",//false为不保存登录
    };
  },
  methods:{
    handlelogin:function()
    {
      if(this.name===localStorage['name'] && this.password===localStorage['password'])
       {
         this.$router.replace('/Home');//如果输入的名字以及密码正确路由跳转至个人页面
       } 
       else if(this.name==='')//名字为空
       {
         alert('用户名不为空');
       }
       else if(this.password==='')//密码为空
       {
         alert('密码不为空');
       }
      else{
        alert('账号不存在,请注册后登录');//查无此号
        }
    },
    handleregister:function()
    {
      this.$router.replace('/register')//点击注册按钮,跳转至注册页面
    },
    //点击保持登录状态触发handlesave
    handlesave:function(){
      this.st="true";//修改登录状态为true
      localStorage.setItem('s',this.st);
      console.log(localStorage.s);
    }
  }
};
</script>

注册

<script>
export default {
    name:'register',
    props: {
    msg: String
  },
  data(){
    return{
      name:"",
      password:"",
      mail:"",
      tel:""
  };
  },methods:{
  //点击完成按钮触发handlefinish
    handlefinish:function()
    {
      if(localStorage['name']===this.name)
      {
        alert("用户名已存在");//如果用户名已存在则无法注册
      }
      else if(this.name==='')
      {
        alert("用户名不能为空");
      }
      else{//将新用户信息存储到localStorage
        localStorage.setItem('name',this.name);
        localStorage.setItem('password',this.password);
        localStorage.setItem('mail',this.mail);
        localStorage.setItem('tel',this.tel);
        localStorage.setItem('s',"false");
        alert("注册成功");
        this.$router.replace('/Login');//完成注册后跳转至登录页面
      }
    }
  }
};
</script>

主页

<script>
export default {
    name:'Home',
    data(){
      return{//获取用户信息到主页
        sname:localStorage.getItem('name'),
        smail:localStorage.getItem('mail'),
        stel:localStorage.getItem('tel'),
        isAuth:"",//是否保持登录状态
      };
    },
    methods:{
      //当点击退出按钮,将不保存登录状态
      logout:function()
      {
        this.isAuth="false";//修改登录状态
        localStorage.setItem('s',this.isAuth);
        this.$router.replace('/login');//页面跳转至登录页面
      }
    }
}
</script>

路由配置文件

通过使用导航守卫的全局前置守卫来实现保持登录状态下,用户重新访问页面时直接进入主页,无需再次登录。
大致语法如下:
router.beforeEach((to,from,next)=>{
//这里执行具体操作
//next调用
})

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "@/components/Home.vue";
import login from "@/components/login.vue";
Vue.use(VueRouter);

const routes = [
  {
  //这里需要将根目录默认为Home,方便实现用户在保持登录 状态下再次登录时直接跳转至主页面
    path:"/",
    redirect:{
      name:"Home"
    }
  },
  {
    path: "/Home",
    name: "Home",
    component: Home,
  },
  {
    path: "/login",
    name: "login",
    component:login
    
  }
  ,{
    path: "/register",
    name: "register",
    component: () =>
      import("@/components/register.vue")
  }
];

const router = new VueRouter({
  mode:'history',
  routes
});

router.beforeEach((to,from,next)=>
{
  //登录及注册页面可以直接进入,而主页面需要分情况
  if(to.path=='/login')
  {
    next();
    console.log(localStorage.s);
  }
  else if(to.path=='/register')
  {
    next();
  }
  else
  {
    if(from.path=="/login")//从登录页面可以直接通过登录进入主页面
    {
      next();
    }
    else{
    	//从/进入,如果登录状态是true,则直接next进入主页面
	      if(localStorage.s === "true")
		    {
		      next();
		      console.log(localStorage['s'])
		    }
	    else {//如果登录状态是false,那么跳转至登录页面,需要登录才能进入主页面
	      next('/login');
	      console.log("需要登录")
	    }
    }
  }
})
export default router;

总结

在此次任务中,需要注意的是localStoragesessionStorage的区别,两者都可用来存储数据,但是localStorage会保留原始数据,即使关闭浏览器,数据仍然存在。而sessionStorage不会保留,关闭浏览器后数据被销毁。由于要求用户在保持登录状态下重新打开浏览器可以不用登录直接进入主页面,所以要用localStorage。

  • 60
    点赞
  • 537
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
以下是一个简单的Vue登录注册页面代码示例: ```html <template> <div> <h2>登录</h2> <form> <div> <label for="username">用户名:</label> <input type="text" id="username" v-model="username" /> </div> <div> <label for="password">密码:</label> <input type="password" id="password" v-model="password" /> </div> <button type="button" @click="handleLogin">登录</button> </form> <hr /> <h2>注册</h2> <form> <div> <label for="new-username">用户名:</label> <input type="text" id="new-username" v-model="newUsername" /> </div> <div> <label for="new-password">密码:</label> <input type="password" id="new-password" v-model="newPassword" /> </div> <div> <label for="confirm-password">确认密码:</label> <input type="password" id="confirm-password" v-model="confirmPassword" /> </div> <button type="button" @click="handleRegister">注册</button> </form> </div> </template> <script> export default { data() { return { username: '', password: '', newUsername: '', newPassword: '', confirmPassword: '', } }, methods: { handleLogin() { // 处理登录逻辑 console.log('登录:', this.username, this.password) }, handleRegister() { // 处理注册逻辑 console.log('注册:', this.newUsername, this.newPassword, this.confirmPassword) }, }, } </script> <style scoped> /* 样式 */ </style> ``` 这个示例包含了一个登录表单和一个注册表单,每个表单都由一些输入字段和一个提交按钮组成。每个输入字段都使用 `v-model` 指令绑定到组件的数据属性上。 登录和注册按钮都有一个 `@click` 监听器,当用户点击按钮时,将会调用相应的处理方法来执行登录或注册逻辑。在这个示例中,这些处理方法只是简单地打印出表单字段中的值。在实际应用中,这些方法将会发出网络请求来与后端服务通信。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值