Technology stack
- Vue.js Main Frame
- Vuex State Management
- Vue-router Routing Management
General process
In the general login process, a front-end scenario is:
- Check Status: Check for login status when entering the page or when routing changes (values stored in
cookie
or 本地存储
);
- 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;
- Log on successfully from the back-end data
session
to save the login status (may need to jump); The login is unsuccessful prompts 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
, after the login route /user_info
. This only needs to be App.vue
put in place router-view
to store and render 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 the vue-router
configuration:
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}, { Span class= "hljs-attr" >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 routing 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 on the Internet can if (!this.getcookie (// If there is no sign-in status, jump to the login page 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 very simple, we vue实例
write in the created
hooks:
// js/app.js...var app = new Vue({ ... created() { this.checkLogin(); }, methods:{ checkLogin(){ ... } }})
In addition, 路由
changes are also required to check the login, the following scenarios (routing changes) if we do not check the login state may occur error:
- When the user enters the page, there is a login status, but the login expires when doing the operation;
- User manually deleted
cookie
/ 本地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 listen to the route, and the functionality that can be leveraged if implemented vue
watch
:
// js/app.js...var app = new Vue({ ... //监听路由检查登录 watch:{ "$route" : ‘checkLogin‘ }, //进入页面时 created() { this.checkLogin(); }, methods:{ checkLogin(){ ... } }})
At this point, we have completed the 一般过程
1th step in the. 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>ExportDefault {... mounted () {Get user information when the component starts to mountThis.getuserinfo (); },Methods: {Request some information from the user 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 configure it before, for example, in the app.js
or write it separately store.js
and introduce it in App.js
(recommended):
// js/app.js// Vuex配置...const store = new Vuex.Store({ state: { domain:‘http://test.example.com‘, //保存后台请求的地址,修改时方便(比方说从测试服改成正式服域名) userInfo: { //保存用户信息 nick: null, ulevel: null, uid: null, portrait: null } }, mutations: { //更新用户信息 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 different website legal characters are not the same, here only do 为空
when the illegal check:
Component/login.vue<template><Divclass="Login"Id="Login" > ...<Divclass="Log-email" ><InputType="Text"Placeholder="Email": class="' Log-input ' + (account== '? ' Log-input-empty ': ')"V-model="Account" ><InputType="Password"Placeholder="Password": class="' Log-input ' + (password== '? ' Log-input-empty ': ')"V-model="Password" ><Ahref="javascript:;"class="Log-btn" @click="Login" >login</A></Div> ...</Div></Template><Script>Import LoadingFrom'./loading.vue 'export default {name: ' Login ', data () {return {isloging: false, account: Password: components:{Loading}, methods:{//login Logic login () {if ( "&& this.password!=") {this.tologin ();}}} </SCRIPT> ...
Here this.toLogin
is the method of login request, in the post
password to the back end is not sent directly, generally according to the rules after the end of the encryption in the send, for example 哈希算法
, the example of the double hash encryption, reference, the approximate implementation of the js/sha1.min.js
following:
...Login Request Tologin () {Generally want to follow the back end to understand the password encryption rulesHere 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 = {AccountThis.account, Password_sha}Set the login statusThis.isloging =TrueRequest back endthis. $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 (//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(){ //删除cookie并跳到登录页 this.isLogouting = true; //请求后端,比如logout.php // this.$http.post(‘eaxmple.com/logout.php‘)... //成功后删除cookie this.delCookie(‘session‘); //重置loding状态 this.isLogouting = false; //跳转到登录页 this.$router.push(‘/login/‘); }...
You are welcome to join the Learning Exchange Group if you encounter any problems or want to acquire learning resources in the learning process.
343599877, we learn the front-end together!
Vue.js the process of writing a SPA login page