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

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

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

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

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

5. 實(shí)現(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: {
}
})設(shè)置登錄的頁面(部分代碼,無法復(fù)制即用,僅作參考)
登錄方法
//登錄方法
login() {
//驗(yàn)證碼的驗(yàn)證
var randStr = this.rand.toString().replace(/,/g, ""); //隨機(jī)生成的驗(yàn)證碼為數(shù)組形式,此處將其轉(zhuǎn)為字符串并去掉中間相隔的逗號(hào)
var codeStr = this.code; //用戶輸入的驗(yàn)證碼
if (randStr.toLowerCase() == codeStr.toLowerCase()) { //比較用戶輸入的與隨機(jī)生成的驗(yàn)證碼,不區(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('您不是管理員,無管理員登錄權(quán)限!');
} else if (this.token == 200) {
if (this.usertyp == "2") { //管理員登錄
this.$message.success('登錄成功!');
this.dialogFormVisible = false; //登錄成功后登錄插槽關(guān)閉
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實(shí)例
this.$message(`歡迎您,管理員 ${this.name}!`)
}, 2000);
console.log(this.usertyp)
} else if (this.usertyp == "") { //普通用戶
this.$message.success('登錄成功!');
this.dialogFormVisible = false; //登錄成功后插槽關(guān)閉
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實(shí)例
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('請輸入正確的驗(yàn)證碼');
}
},退出登錄方法
//退出登錄
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秒后跳轉(zhuǎn)至首頁
}, 2000)
//加()=>{},()=>{} 可解決路由重復(fù)后臺(tái)報(bào)錯(cuò)問題
},掛載階段判斷登錄狀態(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; //登錄成功后插槽關(guān)閉
this.loginReg = false;//隱藏登錄注冊按鈕,顯示歡迎信息
this.name = userInfo.name;
if (userInfo.manage) {
this.manage = true;//顯示管理員登錄信息
} else {
this.user = true;//顯示普通用戶登錄信息
}
}
}提示:小馬使用的是 vue + Element UI,使用其他技術(shù)代碼可能不同,但思路是不變的。
總結(jié)
到此這篇關(guān)于Vue項(xiàng)目如何保持用戶登錄狀態(tài)的文章就介紹到這了,更多相關(guān)Vue保持用戶登錄狀態(tài)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue響應(yīng)式更新機(jī)制及不使用框架實(shí)現(xiàn)簡單的數(shù)據(jù)雙向綁定問題
vue是一款具有響應(yīng)式更新機(jī)制的框架,既可以實(shí)現(xiàn)單向數(shù)據(jù)流也可以實(shí)現(xiàn)數(shù)據(jù)的雙向綁定。這篇文章主要介紹了vue響應(yīng)式更新機(jī)制及不使用框架實(shí)現(xiàn)簡單的數(shù)據(jù)雙向綁定問題,需要的朋友可以參考下2019-06-06
解決Vue運(yùn)行項(xiàng)目報(bào)錯(cuò)proxy?error:?could?not?proxy?request
這篇文章主要給大家介紹了關(guān)于如何解決Vue運(yùn)行項(xiàng)目報(bào)錯(cuò)proxy?error:could?not?proxy?request的相關(guān)資料,Proxy Error指的是代理服務(wù)器無法正確處理請求的錯(cuò)誤,需要的朋友可以參考下2023-08-08

