Vue項目如何保持用戶登錄狀態(tài)(localStorage+vuex刷新頁面后狀態(tài)依然保持)
前言
在前端項目開發(fā)中,實現(xiàn)用戶的登陸注冊功能時常常會有一個問題,那就是我們設置的登錄狀態(tài),在瀏覽器頁面刷新后就消失了,這其實只是因為我們沒有保存用戶狀態(tài)。
這里小馬演示使用的是 localStorage + vuex 方法(其他諸如 sessionStorage、cookie 等用法相同,只是功能有所區(qū)別)。
一、實現(xiàn)效果
實現(xiàn)功能:用戶登錄成功后,刷新瀏覽器頁面或者關閉瀏覽器再次打開網(wǎng)頁后,登錄狀態(tài)依然保持,直到用戶點擊登出。

二、實現(xiàn)步驟及涉及要點
1. 首先在 vuex 中的 state 屬性中添加一個空對象 userInfo{ } 用于保存用戶登錄后的狀態(tài);
涉及要點:
state 屬性(狀態(tài))用于添加多個組件共享的變量,作用類似于 vue 中的 data;

2. 在登錄頁面中,判斷登錄成功后創(chuàng)建對象 userInfo{ },并添加描述登錄狀態(tài)的各屬性,然后將該對象分別存入 localStorage 和 vuex;
涉及要點:
- localStorage 屬性允許訪問 Document 源的 Storage 對象,存儲的數(shù)據(jù)保存在瀏覽器會話中;
- 與 sessionStorage 的唯一區(qū)別就是 localStorage 屬于永久性存儲,除非我們手動清除,而 sessionStorage 屬于臨時存儲,瀏覽器關閉后便會被清空。
- 存:localStorage.setItem('myCat', 'Tom');
- 取:var cat = localStorage.getItem("myCat");
- 刪:localStorage.removeItem("myCat"); 或 localStorage.clear("myCat");
- JSON.stringify() 系列化對象,將返回的對象類型轉為字符串類型;
- this.$store.state,取 vuex 中 state 中的屬性,如:
- this.$store.state.userInfo = userInfo //取出 vuex 中的 userInfo 并賦值為新的 userInfo

3. 在掛載階段,判斷登錄狀態(tài) userInfo;設置相關屬性之后,就可以正常保存登錄狀態(tài)了。
因為 localStorage 為永久保存,所以即使關閉瀏覽器再次打開網(wǎng)頁登錄狀態(tài)依然存在,除非手動清除 localStorage 數(shù)據(jù);

4. 設置登出,清除 localStorage 中的數(shù)據(jù);

5. 實現(xiàn)功能。
三、涉及代碼
vuex(store/index.js)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
userInfo:{}
},
mutations: {
},
actions: {
},
modules: {
}
})設置登錄的頁面(部分代碼,無法復制即用,僅作參考)
登錄方法
//登錄方法
login() {
//驗證碼的驗證
var randStr = this.rand.toString().replace(/,/g, ""); //隨機生成的驗證碼為數(shù)組形式,此處將其轉為字符串并去掉中間相隔的逗號
var codeStr = this.code; //用戶輸入的驗證碼
if (randStr.toLowerCase() == codeStr.toLowerCase()) { //比較用戶輸入的與隨機生成的驗證碼,不區(qū)分大小寫
//獲取登錄接口
axios.post("user/login", {
name: this.name,
password: this.password,
administrator: this.usertyp
}).then(result => {
console.log(result.data);
const code = result.data.code;
this.token = code;
if (this.token == 1003) {
this.$message.error('用戶名或密碼未輸入!');
} else if (this.token == 1001) {
this.$message.error('登錄失敗,請檢查用戶名或者密碼是否正確。');
} else if (this.token == 1005) {
this.$message.error('您不是管理員,無管理員登錄權限!');
} else if (this.token == 200) {
if (this.usertyp == "2") { //管理員登錄
this.$message.success('登錄成功!');
this.dialogFormVisible = false; //登錄成功后登錄插槽關閉
this.loginReg = false;//隱藏登錄注冊按鈕,顯示歡迎信息
this.manage = true;//顯示管理員登錄信息
let userInfo = {
isLogin: true,
manage: true,
name: this.name
};
localStorage.setItem("userInfo", JSON.stringify(userInfo));
this.$store.state.userInfo = userInfo
console.log('this.$store.state.userInfo', this.$store.state.userInfo)
setTimeout(() => { //此處必須使用vue函數(shù),否則this無法訪vue實例
this.$message(`歡迎您,管理員 ${this.name}!`)
}, 2000);
console.log(this.usertyp)
} else if (this.usertyp == "") { //普通用戶
this.$message.success('登錄成功!');
this.dialogFormVisible = false; //登錄成功后插槽關閉
this.loginReg = false;//隱藏登錄注冊按鈕,顯示歡迎信息
this.user = true; //顯示普通用戶登錄信息
let userInfo = {
isLogin: true,
manage: false,
name: this.name
}
localStorage.setItem("userInfo", JSON.stringify(userInfo));
this.$store.state.userInfo = userInfo
setTimeout(() => { //此處必須使用vue函數(shù),否則this無法訪vue實例
this.$message(`歡迎您,尊貴的晉之魂用戶 ${this.name}!`)
}, 2000);
console.log(this.usertyp)
}
this.Cookie.set("UserName", this.name); //將用戶名存到cookie
console.log('登錄狀態(tài)為:' + this.token);
}
})
} else {
this.$message.error('請輸入正確的驗證碼');
}
},退出登錄方法
//退出登錄
logout() {
this.Cookie.remove("UserName");
this.loginReg = true;
this.manage = false;
this.user = false;
this.log_out = false;
localStorage.clear();
setTimeout(() => {
this.$router.push({
path: '/'
}, () => {
}, () => {
});//退出登錄后2秒后跳轉至首頁
}, 2000)
//加()=>{},()=>{} 可解決路由重復后臺報錯問題
},掛載階段判斷登錄狀態(tài)
mounted() {
// 判斷登錄狀態(tài)
let userInfo = JSON.parse(localStorage.getItem('userInfo'));
if (null === userInfo) return;
console.log('userInfo', userInfo.isLogin);
if (userInfo.isLogin) {
this.dialogFormVisible = false; //登錄成功后插槽關閉
this.loginReg = false;//隱藏登錄注冊按鈕,顯示歡迎信息
this.name = userInfo.name;
if (userInfo.manage) {
this.manage = true;//顯示管理員登錄信息
} else {
this.user = true;//顯示普通用戶登錄信息
}
}
}提示:小馬使用的是 vue + Element UI,使用其他技術代碼可能不同,但思路是不變的。
總結
到此這篇關于Vue項目如何保持用戶登錄狀態(tài)的文章就介紹到這了,更多相關Vue保持用戶登錄狀態(tài)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue?socket.io模塊實現(xiàn)聊天室流程詳解
vue-socket.io其實是在socket.io-client(在瀏覽器和服務器之間實現(xiàn)實時、雙向和基于事件的通信)基礎上做了一層封裝,將socket掛載到vue實例上,同時可使用sockets對象輕松實現(xiàn)組件化的事件監(jiān)聽,在vue項目中使用起來更方便2022-12-12
詳解從vue-loader源碼分析CSS Scoped的實現(xiàn)
這篇文章主要介紹了詳解從vue-loader源碼分析CSS Scoped的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09
在vue中使用export?default導出的class類方式
這篇文章主要介紹了在vue中使用export?default導出的class類方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03

