Vue.js implements a spa login page process [recommended]

Vue.js Main Framework
  • VUEX Status Management
  • Vue-router routing management
General process

In a general login process, a front end scheme is:

Check status: when entering the page or when the route changes Check if there is a login state (saved in the cookie or local storage value);

    If there is a login state query login information (UID, avatar, etc. …) and save it; if not, jump to login Page;
  1. At the login page (or login box), the calibration user enters information legal;
  2. After passing the login request after passing, the school inspection is not successful, and it feeds back to the user;
  3. Login success, remove the session information from the backend data to save the login status (may need jump); the login is not successful, prompting the user unsuccessful;
  4. When the user is deleted, the login status is deleted.
  5. Let’s analyze how to do code implementation according to the following steps, all in the code in https://github.com/doterlin/vue-example-login, with more detail Comment helps understand the code.
In this case, it is assumed that the login page is routed as / login, and the route after login is / user_info. This only needs to put Router-View in app.Vue to store and render these two routes.

//component / app.Vue

   
and do Vue-RouteR Configuration: // js / app.jsimport Vue from 'Vue'Import Vuerouter from' Vue-Router'Import Login from '../component/login.vue 'Import Userinfo from' ../component/usefo.vue'vue.use (Vuerouter ); Const Router = New Vuerouter ({routes: [{path: '/ login ", component: login}, {pat:' / user_info ', Component: Userinfo}]}) ...
Check status and jump
We need at two times Check status: 1. When the user opens the page; 2. When the routing changes;
First need to write a method of checking the logging state Checklogin:

 // js / app.js ... var app = new Vue ({data: {}, el: '#app ", render: h => h (app), router, store, methods: {checklogin () {CHECKLOGIN () { / / Check if there is a session // cookie action method in the source code or reference online, if (! This.getCookie ('session')) {// If there is no login state, jump to the login page this. $ Router .push ('/ login');} else {/ / otherwise jump to the page behind the login this. $Router.push ('/ user_info');}}}})   In order to enhance the user experience, when the user opens the page, the front end needs to check if he is already logged in, no need The user logs in again. This implementation is very simple, we write in the Created hook in the Vue instance: 
// js / app.js … var app = new Vue ({..

In addition, the routing changes Check the login, the following scenarios (routing changes) If we do not check the login state, you may have an error:
  There is a login state when entering the page, but when doing operation, just log in to expire;  
User manually deletes cookie / local Storage and do operation;
Users can manually enter (or enter) a route to log in (or from favorites) without logging in

Users entered the login page in the case of login
 These are enough to become the reason for our listening routing, if implemented, Vue's Watch function:   
// js / app.js … var app = new vue ({… // listening routing check login WATCH: {“$ route”: ‘checklogin’}, // CREATED () when entering page {this.checklogin ();}, methods: {checklogin () {…}}})

  • At this way, we have completed step 1 in the general process. Next, how to obtain user personal information.
  • After obtaining user information
  • After successful login, we generally need to display some information from the backend, such as nickname, avatar, grade, etc. … If you are simple, send an HTTP request from the backend; however, the information will be used in multiple routes (such as the UID generally need to be used as a parameter belt in each rear interface), so it is necessary to save to the global state. (Vuex):
  • // Component / Apponent / App.Vue …
Export Default {… mounted () {// Component Before Mount User Information this.getuserinfo ();}, methods: {// Request user information getUserInfo () {this.userinfo = {nick: ‘doterlin’, Ulevel: 20, Uid: ‘10000’, Portrait: ‘Images / Profile.png ‘} // Get Information Request TS. $ http.get (URL, {// Parameters “params”: this.userinfo}. Then ((Response) => {// Success if (Response.Data. Code == 0) {this. $ store.commit (‘updateUserInfo’, this.userinfo);}}, (response) => {// error});}}}

 Of course, we need to configure it before, such asIn writing in App.js or written in Store.js separately (recommendation):   
// js / app.js // vuex configuration .. .const store = new vuex.store ({state: {domain: ‘http://test.example.com’, // Save the address of the background request, convenient when modified (more than the test service is changed to official service domain name) UserInfo: {// Save User Information Nick: Null, Ulevel: Null, Uid: Null, Portrait: Null}}, mutations: {// Update User Information UpdateUserInfo (State, NewuserInfo) {State.userInfo = newuserinfo;}}}

Enter the check and send login request

to prevent some of the characters that do not meet the expected expected and too frequent The request is transmitted to the background, and the front end should check and prevent repetition requests for the user’s input. Of course, the legitimate characters of different websites are different. Here is only an empty check:

// Component / Login.Vue
.   Login   ... 
Import Loading from ‘./loading.Vue’Export Default {name:’ login ‘, Data () {return {isloging: false, account:’ ‘,Password: ”}}, components: {loading}, methods: {// login logic login () {i (this.account! = ” && this.password! = ‘) {this.tologin ();} }}

Here, this is the method of login request. When the POST password is sent directly to the rear end, it is not directly transmitted, which is generally followed. After the rule encryption, the double hash encryption is transmitted, such as the hash algorithm, and examples of example, reference JS / sha1.min.js, which is roughly achieved as follows:
   
… // Login Request TOLOGIN () {// Generally with the rear end to understand the encryption rule / / The hash algorithm used here example is from ./js/sha1.js let password_sha = hex_sha1 (HEX_SHA1 This.Password)); // Need you want to send login parameters let loginparam = {account: this.account, password_sha} //, password_sha} //., please true this 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 period. Let expiredAys = 1000 * 60 * 60 *24 * 15; this.SetCookie (‘session’, response.data.session, expiredays); // jump this. $ Router.push (‘/ user_info’);}}, (response) => {// error }); …

This completes the third, 4, 5 steps. The final step is to log out.

Some need to request unwanted rear ends, key things to delete saved login status:
   
// Component / UserInfo.vue ... logout () {// Remove cookie and jump to the login page this.islogouting = true; // Request the rear, such as logout.php // this. $ http.post ('eaxmple.com/logout.php') ... // Remove cookie this.delcookie ('session'); // Reset Loding status this.islogouting = false; // Jump to Login page this. $ Router.push ('/ login /');} ...
The above is all the content of this article, and it is desirable to learn from the content of this article. Or work can bring a certain help, and I hope to support Tumi Cloud!
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment