Vue.js實(shí)現(xiàn)一個SPA登錄頁面的過程【推薦】
技術(shù)棧
- vue.js 主框架
- vuex 狀態(tài)管理
- vue-router 路由管理
一般過程
在一般的登錄過程中,一種前端方案是:
- 檢查狀態(tài):進(jìn)入頁面時(shí)或者路由變化時(shí)檢查是否有登錄狀態(tài)(保存在cookie或者本地存儲的值);
- 如果有登錄態(tài)則查詢登錄信息(uid,頭像等...)并保存起來;如果沒有則跳轉(zhuǎn)到登錄頁;
- 在登錄頁面(或者登錄框),校檢用戶輸入信息是否合法;
- 校檢通過后發(fā)送登錄請求;校檢不成功則反饋給用戶;
- 登錄成功則從后端數(shù)據(jù)中取出session信息保存登錄狀態(tài)(可能需要跳轉(zhuǎn));登錄不成功則提示用戶不成功;
- 用戶做出注銷操作時(shí)刪除登錄狀態(tài)。
下面我根據(jù)列出的步驟一一分析如何做代碼實(shí)現(xiàn),所有在代碼在https://github.com/doterlin/vue-example-login中,并帶有較詳細(xì)注釋幫助理解代碼。
在此之前假設(shè)登錄頁面路由為/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.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
}]
})
...
檢查狀態(tài)與跳轉(zhuǎn)
在兩個時(shí)候我們需要檢查狀態(tài):1.用戶打開頁面時(shí); 2.路由發(fā)生變化時(shí);
首先需要寫好一個檢查登錄態(tài)的方法checkLogin:
// js/app.js
...
var app = new Vue({
data: {},
el: '#app',
render: h => h(App),
router,
store,
methods:{
checkLogin(){
//檢查是否存在session
//cookie操作方法在源碼里有或者參考網(wǎng)上的即可
if(!this.getCookie('session')){
//如果沒有登錄狀態(tài)則跳轉(zhuǎn)到登錄頁
this.$router.push('/login');
}else{
//否則跳轉(zhuǎn)到登錄后的頁面
this.$router.push('/user_info');
}
}
}
})
為了提升用戶體驗(yàn),當(dāng)用戶打開頁面時(shí)前端需要檢查他是否已經(jīng)登錄,不需要用戶再次登錄。這個實(shí)現(xiàn)很簡單,我們在vue實(shí)例的created鉤子里寫好:
// js/app.js
...
var app = new Vue({
...
created() {
this.checkLogin();
},
methods:{
checkLogin(){
...
}
}
})
另外,路由發(fā)生變化時(shí)也需要檢查登錄,以下情景(路由變化)如果我們不檢查登錄態(tài)可能會發(fā)生錯誤:
- 用戶在進(jìn)入頁面時(shí)存在登錄狀態(tài),但在做操作時(shí)正好登錄過期了;
- 用戶手動刪除了cookie/本地storage并做操作;
- 用戶在未登錄的情況下手動輸入(或者從收藏夾進(jìn)入)某個需要登錄的路由
- 用戶在已登錄的情況下進(jìn)入登錄頁路由
這些足夠成為我們監(jiān)聽路由的理由,實(shí)現(xiàn)的話可以利用vue的watch功能:
// js/app.js
...
var app = new Vue({
...
//監(jiān)聽路由檢查登錄
watch:{
"$route" : 'checkLogin'
},
//進(jìn)入頁面時(shí)
created() {
this.checkLogin();
},
methods:{
checkLogin(){
...
}
}
})
至此,我們就完成了一般過程中的第1步。接下來實(shí)現(xiàn)如何獲取用戶個人信息。
獲取用戶信息
在成功登錄后,我們一般需要從后端顯示用戶的一些信息,比如昵稱,頭像,等級等等...獲取的話很簡單,發(fā)一個http請求從后端拉?。坏且话氵@些信息會在多的路由用到(比如uid一般都需要在各個后端接口中作為參數(shù)帶上),所以需要保存到全局狀態(tài)中(vuex):
// component/App.vue
...
<script>
export default {
...
mounted(){
//組件開始掛載時(shí)獲取用戶信息
this.getUserInfo();
},
methods: {
//請求用戶的一些信息
getUserInfo(){
this.userInfo = {
nick: 'Doterlin',
ulevel: 20,
uid: '10000',
portrait: 'images/profile.png'
}
//獲取信息請求
ts.$http.get(url, {
//參數(shù)
"params": this.userInfo
}).then((response) => {
//Success
if(response.data.code == 0){
this.$store.commit('updateUserInfo', this.userInfo);
}
}, (response) => {
//Error
});
}
}
}
</script>
...
當(dāng)然我們需要在之前配置好,比如在寫在app.js或者單獨(dú)寫成store.js并在app.js引入(推薦):
// js/app.js
// Vuex配置
...
const store = new Vuex.Store({
state: {
domain:'http://test.example.com', //保存后臺請求的地址,修改時(shí)方便(比方說從測試服改成正式服域名)
userInfo: { //保存用戶信息
nick: null,
ulevel: null,
uid: null,
portrait: null
}
},
mutations: {
//更新用戶信息
updateUserInfo(state, newUserInfo) {
state.userInfo = newUserInfo;
}
}
})
...
輸入校驗(yàn)和發(fā)送登錄請求
為了防止一些不符合預(yù)期的字符和過于頻繁的請求傳到后臺,前端要對用戶的輸入進(jìn)行校驗(yàn)和防止重復(fù)請求。當(dāng)然不同網(wǎng)站的合法字符不一樣,這里只做為空時(shí)不合法的校驗(yàn):
//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密碼到后端時(shí)不是直接發(fā)送,一般會按照后端定的規(guī)則加密后在發(fā)送,比如哈希算法,例子進(jìn)行了的雙重哈希加密,引用了js/sha1.min.js,大致實(shí)現(xiàn)如下:
...
//登錄請求
toLogin(){
//一般要跟后端了解密碼的加密規(guī)則
//這里例子用的哈希算法來自./js/sha1.min.js
let password_sha = hex_sha1(hex_sha1( this.password ));
//需要想后端發(fā)送的登錄參數(shù)
let loginParam = {
account: this.account,
password_sha
}
//設(shè)置在登錄狀態(tài)
this.isLoging = true;
//請求后端
this.$http.post( 'example.com/login.php', {
param: loginParam).then((response) => {
if(response.data.code == 1){
//如果登錄成功則保存登錄狀態(tài)并設(shè)置有效期
let expireDays = 1000 * 60 * 60 * 24 * 15;
this.setCookie('session', response.data.session, expireDays);
//跳轉(zhuǎn)
this.$router.push('/user_info');
}
}, (response) => {
//Error
});
...
這樣就完成了第3,4,5個步驟了。最后一步就是注銷。
注銷
注銷時(shí)有的需要請求后端有的不需要,關(guān)鍵的事要刪除保存的登錄狀態(tài):
// component/UserInfo.vue
...
logout(){
//刪除cookie并跳到登錄頁
this.isLogouting = true;
//請求后端,比如logout.php
// this.$http.post('eaxmple.com/logout.php')...
//成功后刪除cookie
this.delCookie('session');
//重置loding狀態(tài)
this.isLogouting = false;
//跳轉(zhuǎn)到登錄頁
this.$router.push('/login/');
}
...
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!
- 詳解vuex中的this.$store.dispatch方法
- Vue實(shí)現(xiàn)數(shù)據(jù)表格合并列rowspan效果
- 在Vuex使用dispatch和commit來調(diào)用mutations的區(qū)別詳解
- 基于Vue的SPA動態(tài)修改頁面title的方法(推薦)
- vue中SPA單頁面應(yīng)用程序詳解
- 詳解vue 單頁應(yīng)用(spa)前端路由實(shí)現(xiàn)原理
- 淺談Vue SPA 首屏加載優(yōu)化實(shí)踐
- VUE解決微信簽名及SPA微信invalid signature問題(完美處理)
- Vue SPA 路由跳轉(zhuǎn)無法回到頂部問題排查與解決
相關(guān)文章
vue3?reactive數(shù)據(jù)更新視圖不更新問題解決
這篇文章主要為大家介紹了vue3?reactive數(shù)據(jù)更新視圖不更新問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
vue-cli單頁面預(yù)渲染seo-prerender-spa-plugin操作
這篇文章主要介紹了vue-cli單頁面預(yù)渲染seo-prerender-spa-plugin操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
VueJS 集成 Medium Editor的示例代碼 (自定義編輯器按鈕)
本篇文章主要介紹了VueJS 集成 Medium Editor的示例代碼 (自定義編輯器按鈕),具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08
Vue3實(shí)現(xiàn)獲取驗(yàn)證碼按鈕倒計(jì)時(shí)效果
這篇文章主要介紹了Vue3實(shí)現(xiàn)獲取驗(yàn)證碼按鈕倒計(jì)時(shí)效果,用戶點(diǎn)擊獲取驗(yàn)證碼按鈕,發(fā)送請求給后端,按鈕失效,并且開始倒計(jì)時(shí)60秒;在此期間,用戶無法再次點(diǎn)擊按鈕,即使用戶刷新頁面,倒計(jì)時(shí)依然存在,直到倒計(jì)時(shí)完畢,按鈕恢復(fù),感興趣的小伙伴跟著小編一起來看看吧2024-10-10
VUE+ElementUI下載文件的幾種方式(小結(jié))
本文主要介紹了VUE+ElementUI下載文件的幾種方式(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01

