Vue.js實現一個SPA登入頁面的過程【推薦】,vue.jsspa登入頁面
技術棧
- vue.js 主架構
- vuex 狀態管理
- vue-router 路由管理
一般過程
在一般的登入過程中,一種前端方案是:
- 檢查狀態:進入頁面時或者路由變化時檢查是否有登入狀態(儲存在cookie或者本機存放區的值);
- 如果有登入態則查詢登入資訊(uid,頭像等...)並儲存起來;如果沒有則跳轉到登入頁;
- 在登入頁面(或者登入框),校檢使用者輸入資訊是否合法;
- 校檢通過後發送登入請求;校檢不成功則反饋給使用者;
- 登入成功則從後端資料中取出session資訊儲存登入狀態(可能需要跳轉);登入不成功則提示使用者不成功;
- 使用者做出登出操作時刪除登入狀態。
下面我根據列出的步驟一一分析如何做代碼實現,所有在代碼在https://github.com/doterlin/vue-example-login中,並帶有較詳細注釋協助理解代碼。
在此之前假設登入頁面路由為/login,登入後的路由為/user_info。這樣只需要在App.vue放好router-view用於存放和渲染這兩個路由。
// component/App.vue<template><div class="container" id="app"> <transition name="fade"> <keep-alive> <router-view></router-view> </keep-alive> </transition></div></template>...
並做好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 }]})...
檢查狀態與跳轉
在兩個時候我們需要檢查狀態:1.使用者開啟頁面時; 2.路由發生變化時;
首先需要寫好一個檢查登入態的方法checkLogin:
// js/app.js...var app = new Vue({ data: {}, el: '#app', render: h => h(App), router, store, methods:{ checkLogin(){ //檢查是否存在session //cookie操作方法在源碼裡有或者參考網上的即可 if(!this.getCookie('session')){ //如果沒有登入狀態則跳轉到登入頁 this.$router.push('/login'); }else{ //否則跳轉到登入後的頁面 this.$router.push('/user_info'); } } }})
為了提升使用者體驗,當使用者開啟頁面時前端需要檢查他是否已經登入,不需要使用者再次登入。這個實現很簡單,我們在vue執行個體的created鉤子裡寫好:
// js/app.js...var app = new Vue({ ... created() { this.checkLogin(); }, methods:{ checkLogin(){ ... } }})
另外,路由發生變化時也需要檢查登入,以下情景(路由變化)如果我們不檢查登入態可能會發生錯誤:
- 使用者在進入頁面時存在登入狀態,但在做操作時正好登入到期了;
- 使用者手動刪除了cookie/本地storage並做操作;
- 使用者在未登入的情況下手動輸入(或者從收藏夾進入)某個需要登入的路由
- 使用者在已登入的情況下進入登入頁路由
這些足夠成為我們監聽路由的理由,實現的話可以利用vue的watch功能:
// js/app.js...var app = new Vue({ ... //監聽路由檢查登入 watch:{ "$route" : 'checkLogin' }, //進入頁面時 created() { this.checkLogin(); }, methods:{ checkLogin(){ ... } }})
至此,我們就完成了一般過程中的第1步。接下來實現如何擷取使用者個人資訊。
擷取使用者資訊
在成功登入後,我們一般需要從後端顯示使用者的一些資訊,比如暱稱,頭像,等級等等...擷取的話很簡單,發一個http請求從後端拉取;但是一般這些資訊會在多的路由用到(比如uid一般都需要在各個後端介面中作為參數帶上),所以需要儲存到全域狀態中(vuex):
// component/App.vue...<script>export default { ... mounted(){ //組件開始掛載時擷取使用者資訊 this.getUserInfo(); }, methods: { //請求使用者的一些資訊 getUserInfo(){ this.userInfo = { nick: 'Doterlin', ulevel: 20, uid: '10000', portrait: 'images/profile.png' } //擷取資訊請求 ts.$http.get(url, { //參數 "params": this.userInfo }).then((response) => { //Success if(response.data.code == 0){ this.$store.commit('updateUserInfo', this.userInfo); } }, (response) => { //Error }); } }}</script>...
當然我們需要在之前配置好,比如在寫在app.js或者單獨寫成store.js並在app.js引入(推薦):
// 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; } }})...
輸入校正和發送登入請求
為了防止一些不符合預期的字元和過於頻繁的請求傳到後台,前端要對使用者的輸入進行校正和防止重複請求。當然不同網站的合法字元不一樣,這裡只做為空白時不合法的校正:
//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(){ if(this.account!='' && this.password!=''){ this.toLogin(); } }}</script>...
這裡的this.toLogin就是登入請求的方法,在post密碼到後端時不是直接發送,一般會按照後端定的規則加密後在發送,比如雜湊演算法,例子進行了的雙重雜湊加密,引用了js/sha1.min.js,大致實現如下:
... //登入請求 toLogin(){ //一般要跟後端瞭解密碼的加密規則 //這裡例子用的雜湊演算法來自./js/sha1.min.js let password_sha = hex_sha1(hex_sha1( this.password )); //需要想後端發送的登入參數 let loginParam = { account: this.account, password_sha } //設定在登入狀態 this.isLoging = true; //請求後端 this.$http.post( 'example.com/login.php', { param: loginParam).then((response) => { if(response.data.code == 1){ //如果登入成功則儲存登入狀態並設定有效期間 let expireDays = 1000 * 60 * 60 * 24 * 15; this.setCookie('session', response.data.session, expireDays); //跳轉 this.$router.push('/user_info'); } }, (response) => { //Error });...
這樣就完成了第3,4,5個步驟了。最後一步就是登出。
登出
登出時有的需要請求後端有的不需要,關鍵的事要刪除儲存的登入狀態:
// 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/'); }...
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的協助,同時也希望多多支援幫客之家!