General process
In the general login process, a front-end scenario is:
- Check Status: Check for login status (stored in cookie or locally stored value) when entering page or when routing changes;
- Query login information (UID, avatar, etc.) if there is login state. and save it, if not, jump to the login page;
- In the login page (or login box), the test user input information is legal;
- Send the login request after the school check is passed, and feedback to the user if the school check is unsuccessful;
- Successful login will remove the session information from the backend data to save the login status (may need to jump); The unsuccessful login will prompt the user to be unsuccessful;
- The logon state is removed when the user makes a logoff operation.
Here I analyze how to do code implementation, all in code in Https://github.com/doterlin/vue-example-login, with more detailed comments to help understand the code.
Before this, assume that the login page is routed to/login, and that the route after login is/user_info. This only needs to be put in App.vue Router-view for storing and rendering these two routes.
Component/app.vue<template><div class= "Container" id= "App" > <transition name= "Fade" > < keep-alive> <router-view></router-view> </keep-alive> </transition></div> </template>, .....
And do vue-router configuration:
// js/app.jsimport vue from ' Vue' vue-router'. /component/login.vue ". /component/userinfo.vue 'new'/login '/user_info ', Component:userinfo}]} )...
Check status and Jump
At two times we need to check the status: 1. When the user opens the page; 2. When the routing changes;
First, you need to write a method to check the login state checklogin:
//Js/app.js...varApp =NewVue ({data: {}, el:' #app ', Render:h=h (App), router, store, methods:{Checklogin () {//Check if there is a session //cookie operation method in the source code or reference on the Internet can be if(! This. GetCookie (' Session ')){ //Jump to the login page if there is no sign-in status This. $router. Push ('/login '); }Else{ //otherwise jump to the post-login page This. $router. Push ('/user_info '); } } }})
To improve the user experience, the front end needs to check if the user is logged in when the page is opened and does not require the user to log in again. This implementation is simple and we write in the created hook of the Vue instance:
// Js/app.js ... var New this. Checklogin ();}, methods:{Checklogin () { ...}})
In addition, when routing changes, you also need to check the login, the following scenario (routing changes) if we do not check the login state, an error may occur:
- When the user enters the page, there is a login status, but the login expires when doing the operation;
- User manually deleted cookie/local storage and do the operation;
- A user manually enters (or enters from a collection) without logging in a route that needs to be signed in
- User enters login page routing when logged in
This is enough to be the reason we're listening to the route, so we can take advantage of Vue's Watch feature:
// Js/app.js ... var New // listen for routing check login "$route": ' Checklogin'// Enter page this. Checklogin ();}, methods:{Checklogin () { ...}})
So far, we have completed the 1th step in the general process. The next step is how to get the user's personal information.
Get user Information
After successful login, we usually need to display some information from the backend, such as nickname, Avatar, level and so on. Getting the words is simple, send an HTTP request to pull from the backend, but generally this information will be used in many routes (such as UID generally need to be in each back-end interface as a parameter band), so you need to save to the global State (VUEX):
Component/app.vue...<script>export Default {... mounted () {///component Gets user information This.getuserinfo () when starting mount, methods: {// Ask the user for some information GetUserInfo () { this.userinfo = { Nick: ' Doterlin ', ulevel:20, uid: ' 10000 ', portrait: ' Images/profile.png ' } //Get Information request ts. $http. Get (URL, { //parameter "params": This.userinfo }). Then (response) = { //success if (Response.data.code = = 0) {This . $store. Commit (' Updateuserinfo ', This.userinfo),}} , (response) = { //error });}} </script>, .....
Of course we need to be configured before, for example, writing in App.js or individually written store.js and introduced in App.js (recommended):
js/app.js//Vuex configuration ... const store = new Vuex.store ({state: {domain: ' http://test.example.com ',//Save the address of the background request, Easy to modify (e.g. change from test to formal) UserInfo: {//Save user Information nick:null, ulevel:null, uid:null, Portrait:null}}, Mutations: {//update user Information Updateuserinfo (state, Newuserinfo) { state.userinfo = Newuserinfo;}}) ...
Enter the checksum to send the login request
To prevent some non-conforming characters and overly frequent requests from being sent to the background, the front end verifies the user's input and prevents duplicate requests. Of course, the legal characters of different sites are not the same, here only as empty when the illegal check:
//Component/login.vue<template><div class= "Login" id= "Login" > ... <div class= "Log-email" > <input type= "text" placeholder= "email": class= "' log-input ' + (account== '? ') Log-input-empty ': ') "v-model=" account "><input type=" password "placeholder=" password ": class=" ' Log-input ' + ( password== '? ' Log-input-empty ': ') "v-model=" password "> <a href=" javascript:; "rel=" External nofollow "class=" Log-btn "@click =" Login ">Login</a> </div> ...</div></template><script>Import Loading from'./loading.vue 'Exportdefault{name:' Login ', data () {return{isloging:false, Account:‘‘, Password:‘‘}}, components:{Loading}, methods:{//Login LogicLogin () {if( This. account!= ' && This. password!= '){ This. Tologin (); } }}</script>, .....
Here This.tologin is the method of the login request, in the post password to the back end is not sent directly, generally according to the rules of the back end after encryption in the sending, such as hashing algorithm, the example of the double hash encryption, referring to Js/sha1.min.js, the approximate implementation of the following:
... //Login RequestTologin () {//generally want to follow the back end to understand the password encryption rules //Here The example uses a hashing algorithm from the./js/sha1.min.jsLet Password_sha = Hex_sha1 (HEX_SHA1 ( This. password)); //login parameters that need to be sent back-endLet Loginparam ={account: This. Account, Password_sha}//Set the login status This. isloging =true; //Request back end This. $http. Post (' example.com/login.php ', {param:loginparam). Then (response)= { if(Response.data.code = = 1){ //If the login is successful, save the login status and set the validity periodLet expiredays = 1000 * 60 * 60 * 24 * 15; This. Setcookie (' Session ', Response.data.session, expiredays); //Jump This. $router. Push ('/user_info '); }}, (response)= { //Error });...
This completes the first 3,4,5 step. The final step is to log out.
Cancellation
There is no need to request the backend when you log out, the key thing to delete the saved login state:
//Component/userinfo.vue... logout () {//Delete Cookie and skip to login page This. islogouting =true; //request back end, such as logout.php //This . $http. Post (' eaxmple.com/logout.php ') ... //Delete cookies after success This. Delcookie (' Session '); //Reset loding Status This. islogouting =false; //Jump to login page This. $router. Push ('/login/'); }...