前端如何写登录页面

1,069 阅读1分钟

登录页面的主要思路有很多,这里提供两个先
第一是我目前项目里面老人写的,逻辑是在每次请求时先对后端返回的状态码做判断,如果是无权限或者失效状态,那就使用window.location.href来跳转到登录页面,但是有个问题,就是页面渲染的顺序问题,主页会先渲染然后到请求时才会判断请求结果,这个有延迟,login弹出不是先弹出,会先看到主页。这里要看你的项目是否接受这个问题。
第二个就是利用路由钩子router.beforeEach()参数有to from next来做,先进入login,在进入之前查sessionStorage或者本地的cookie或者localStorage里面的登录状态(这个是之前登录放在本地的,可能包括用户名和密码和有效期)。如果不需要登录,那就让进入login的router的next里面写入主页的path,这样就是在函数执行完后中断当前路由直接进入next里面的path。这样就进到主页了。如果是没有的话,或者过期了,那么就进入login页面发起axios请求,来创建登录状态了,要用sessionStorage还是localStorage还是cookie,什么时候删除本地的登录状态码,就要看项目了,不推荐使用localStorage,这个需要手动删除,注意最好是手动删除一下。这里的连接用了sessionstorage来做的,这里要把它为空的状态判断到。
注意token是从服务器生成的,放在cookie中

www.jianshu.com/p/2578cc444…

存储位置的差别
segmentfault.com/a/119000001…

<html>
  <head>
    <base href="<%=basePath%>">
    <title>系统登录</title>
    <script type="text/javascript">
    	function check(){
    		if(form1.username.value==""){
    			alert("请输入用户名称");
    			form1.username.focus();
    			return false;
    		}
          if(form1.username.value.length<6 || form1.username.value.length>20){
    			alert("用户名称长度应该保持在6-20之内");
    			form1.username.focus();
    			return false;
    		}
    		if(form1.password.value==""){
    			alert("请输入登录密码");
    			form1.password.focus();
    			return false;
    		}
        if(form1.password.value.length<5 || form1.password.value.length>15){
    			alert("登录密码长度应该保持在5-15之内");
    			form1.username.focus();
    			return false;
    		}
    		return true;
    	}
    </script>
  </head>
  <body>
    <h1 align="center">系统登录</h1>
    <hr/>
    <form action="user.html" name="form1" onsubmit="return check();" method="post">
    	<table align="center" border="1" width="500">
    		<tr>
    			<td align="right">用户名称:</td>
    			<td><input type="text" name="username" value="qzm123" /></td>
    		</tr>
    		<tr>
    			<td align="right">登录密码:</td>
    			<td><input type="password" name="password" value="Test_002"/></td>
    		</tr>
    		<tr>
    			<td  colspan="2" align="center"><input type="submit" value="  登 录  "/></td>
    		</tr>
    	</table>
    </form>
  </body>
</html>