Technology StackVue.js Main frame Vuex state management Vue-router Routing Management
General Process
In the general login process, a front-end scheme is: Check the status: When the page or route changes to check whether there is a login status (stored in cookies or locally stored values), if there is a login state query login information (UID, avatar, etc.) and save it, and if not, jump to the login page; in the login page (or login box), the school checks whether the user input information is legal; After the school check Pass, send the login request; Feedback to the user when the school check is unsuccessful; Login success then remove session information from back-end data to save login status (may need to jump); The unsuccessful login prompts the user to be unsuccessful, and the user deletes the login status when the logout operation is made.
I'll follow the steps listed below to analyze how to do the code implementation, all in the code in Https://github.com/doterlin/vue-example-login, and with a more detailed comment to help understand the code.
Before this, assume that the login page is routed to/login, and the route after login is/user_info. This only requires that the Router-view be placed in the 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>
...
And do a good job Vue-router configuration:
Js/app.js
import 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 jump
At two times we need to check the status: 1. When the user opens the page; 2. When the route changes;
First, you need to write a method to check the login state checklogin:
Js/app.js ...
var app = new Vue ({
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 online can be
if (!this.getcookie (' Session ')) {
/ Jump to login page if no login status this
. $router. Push ('/login ');
} else{
//Otherwise jump to the page after login this
. $router. Push ('/user_info ');}}}
)
In order to improve the user experience, when the user opens the page, the front end needs to check that he is logged in and does not require the user to log in again. This implementation is simple, we write in the Vue instance of the created hook:
Js/app.js ...
var app = new Vue ({
...
) Created () {
this.checklogin ();
},
methods:{
checklogin () {
...
}
}})
In addition, the routing changes also need to check logins, the following scenario (routing change) if we do not check the logon state may be an error: The user entered the page when there is a login status, but when doing the operation is logged out of date, the user manually deleted the cookie/local storage and do the operation; Manual input (or entry from Favorites) by a user without logging on to a routing user who needs to log on in a login page
These are enough to be the reason for our listening routing, and we can use the Vue watch function:
Js/app.js ...
var app = new Vue ({
...
) Listen for routing check login
watch:{
"$route": ' Checklogin '
},
//When entering page
created () {
this.checklogin ();
} ,
methods:{
checklogin () {
...}}
}
)
At this point, we have completed the 1th step in the general process. The next implementation is how to get user personal information. Get user Information
After the successful login, we generally need to display the user's information from the backend, such as nickname, Avatar, grade, etc. ... It's easy to get an HTTP request pulled from the back end, but generally this information is used in many routes (for example, the UID typically needs to be taken as a parameter in each back-end interface), so it needs to be saved to the global State (VUEX):
Component/app.vue ...
<script>
Export Default {...
Mounted () {
///component Gets user information
this.getuserinfo () at the beginning of Mount ();
},
methods: {
//Request some information from the user
GetUserInfo () {
This.userinfo = {
Nick: ' Doterlin ',
ulevel:20,
uid: ' 10000 ',
portrait: ' images/ Profile.png '
}
//obtain 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 configure it before, for example, in writing in App.js or written separately in 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 (for example, change from the test suit to the formal 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;
}
}
})
...
input Checksum send login request
In order to prevent some unexpected characters and too frequent requests to the background, the front-end to the user's input to verify and prevent duplicate requests. Of course, the legal characters of different sites are not the same, here only to be null-time illegal checksum:
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:;" 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> ...
Here the This.tologin is the method of login request, in the post password to the backend is not sent directly, usually in accordance with the rules of the backend after the encryption in the send, such as hashing algorithm, example of the double hash encryption, cited the Js/sha1.min.js, the general implementation of the following:
..//Login Request Tologin () {///generally to the backend to understand the cryptographic rules of the password//Here The example uses a hash algorithm from./js/sha1.min.js Let Pass
Word_sha = HEX_SHA1 (HEX_SHA1 (This.password));
Need to think back-end send login parameter let Loginparam = {account:this.account, Password_sha}
Set in login state this.isloging = true;
Request backend this. $http. Post (' example.com/login.php ', {param:loginparam). Then ((response) => { if (Response.data.code = 1) {//If the login succeeds, 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 first 3,4,5 step. The final step is to log off. Log Off
Log off when some need to request the backend some do not need, the key thing to delete the saved login status:
Component/userinfo.vue ...
Logout () {
//delete cookie and skip to login page
this.islogouting = true;