Vue. js implements a SPA login page [recommended], vue. jsspa login page

Source: Internet
Author: User

Vue. js implements a SPA login page [recommended], vue. jsspa login page

Technology Stack

  • Main framework of vue. js
  • Vuex Status Management
  • Vue-router route management

General Process

In the General login process, a front-end solution is:

  1. Check status: When the page is displayed or the route changes, check whether there is a logon status (the value stored in the cookie or local storage );
  2. If the logon status is available, query and save the logon information (uid, profile picture, etc.). If not, go to the logon page;
  3. On the logon page (or in the logon box), check whether the entered information is valid;
  4. After the verification passes, a logon request is sent. If the verification fails, the request is sent to the user;
  5. If the logon succeeds, the session information is retrieved from the backend data to save the logon status (you may need to jump to it). If the logon fails, the system prompts that the user is not successful;
  6. The user deletes the logon status when logging out.

Next, I will analyze how to implement the Code according to the listed steps. All the code in https://github.com/doterlin/vue-example-login will be explained in detail.

Assume that the logon page is/login, And the logon route is/user_info. In this way, you only need to set the router-view in App. vue to store and render the 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>...

Configure vue-router:

// js/app.jsimport Vue from 'vue'import VueRouter from 'vue-router'import Login from '../component/Login.vue'import UserInfo from '../component/UserInfo.vue'Vue.use(VueRouter);const router = new VueRouter({ routes: [{ path: '/login', component: Login }, { path: '/user_info', component: UserInfo }]})...

Check status and redirect

In two cases, we need to check the status: 1. When the user opens the page; 2. When the route changes;

First, you need to write a checkLogin method to check the logon status:

// Js/app. js... var app = new Vue ({data :{}, el: '# app', render: h => h (app), router, store, methods: {checkLogin () {// check whether a session exists // The cookie operation method can be found in the source code or can be found on the Internet if (! This. getCookie ('session ') {// if no logon status exists, the logon page is displayed. this. $ router. push ('/login');} else {// otherwise jump to the logon page this. $ router. push ('/user_info ');}}}})

To improve the user experience, when a user opens the page, the front-end needs to check whether the user has logged on and does not need to log on again. This implementation is very simple. Let's write it in the created hook of the vue instance:

// js/app.js...var app = new Vue({ ... created() { this.checkLogin(); }, methods:{ checkLogin(){  ... } }})

In addition, you also need to check the logon status when the route changes. In the following scenarios (route changes), if we do not check the logon status, an error may occur:

  • The user's logon status exists when entering the page, but the logon expired exactly when performing the operation;
  • The user manually deletes the cookie/Local storage and performs operations;
  • Manually enter (or enter from favorites) a route to log on without logon
  • If you have logged on, go to the logon page.

These are enough reasons for us to listen to the route. If we do so, we can use the watch function of vue:

// Js/app. js... var app = new Vue ({... // monitor route check logon watch: {"$ route": 'checklogin'}, // created () {this. checkLogin () ;}, methods: {checkLogin (){...}}})

So far, we have completed Step 1 in the general process. Next, we will implement how to obtain user personal information.

Obtain user information

After successful logon, we generally need to display User information from the backend, such as nicknames, portraits, levels, and so on... it is easy to get the information. Send an http request to pull the information from the backend. However, this information is generally used in multiple routes (for example, uid must be included as a parameter in each backend interface ), therefore, you need to save it to the global state (vuex ):

// Component/App. vue... <script> export default {... mounted () {// obtain user information when the component starts mounting this. getUserInfo () ;}, methods: {// request the user's information getUserInfo () {this. userInfo = {nick: 'doterlin', ulevel: 20, uid: '000000', portrait: 'images/profile.png '} // Request for Information 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 configure it before, for example, writing it in app. js or writing it separately as store. js and introducing it 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, which is convenient for modification (for example, change from test server to official server 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 verification and send login request

In order to prevent some non-conforming characters and too frequent requests from being sent to the background, the front-end should verify the user's input to prevent repeated requests. Of course, the valid characters of different websites are different. Here, the verification is only invalid when it is null:

// 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 'export default {name: 'login', data () {return {isLoging: false, account: '', password:'' }}, components: {Loading }, methods: {// login logic login () {if (this. account! = ''& This. password! = '') {This. toLogin () ;}}</script>...

This. toLogin is the login request method. When the post password is sent to the backend, it is not directly sent. It is generally encrypted and sent according to the backend rules, such as the hash algorithm, the example uses double hash encryption and references js/sha1.min. js, roughly implemented as follows:

... // Login request toLogin () {// generally, you need to know the password encryption rules with the backend. // The hash algorithm used here is from. /js/sha1.min. js let password_sha = hex_sha1 (hex_sha1 (this. password); // the login parameter that needs to be sent by the backend. let loginParam = {account: this. account, password_sha} // set the logon status this. isLoging = true; // request the backend this. $ http. post ('example. com/login. php', {param: loginParam ). then (response) => {if (response. data. code = 1) {// If the logon succeeds, save the logon status and set the validity period to let expireDays = 1000*60*60*24*15; this. setCookie ('session ', response. data. session, expireDays); // jump to this. $ router. push ('/user_info') ;},( response) =>{// Error });...

This completes step 3, 4 and 5. The last step is to log out.

Cancel

When logging out, some requests are not required at the backend. The key is to delete the saved logon status:

// Component/UserInfo. vue... logout () {// Delete the cookie and jump to the logon page this. isLogouting = true; // request the backend, such as logout. php // this. $ http. post ('axmple. com/logout. php ')... // Delete the cookie this. delCookie ('session '); // reset loding status this. isLogouting = false; // jump to the logon page this. $ router. push ('/login /');}...

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.