前端Vue如何獲取登錄的用戶名或用戶id代碼實例
一、使用全局狀態(tài)管理(Vuex)獲取登錄用戶名
創(chuàng)建 Vuex store,并在其中定義一個用于存儲用戶名的狀態(tài)。
// store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
username: '', // 存儲登錄用戶名的狀態(tài)
userid:'',//儲存登錄用戶id
},
mutations: {
setUsername(state, username) {
state.username = username;
},
setUserid(state, userid) {
state.userid = userid;
},
},
});在登錄成功后,將用戶名保存到 Vuex store 中。
// 登錄成功后的處理
this.$store.commit('setUsername', username);
this.$store.commit('setUserid', userid);在需要獲取登錄用戶名的組件中,使用計算屬性來獲取用戶名。
<template>
<div>
<p>Welcome, {{ username }}</p>
</div>
</template>
<script>
export default {
computed: {
username() {
return this.$store.state.username;
},
userid() {
return this.$store.state.userid;
},
},
};
</script>二、使用瀏覽器本地存儲(localStorage)獲取登錄用戶id
1.在登錄成功后getUserid是我寫的后端接口函數(shù),SetUserId將用戶id保存到 localStorage 中。
getUserid()
.then(response => {
// 獲取用戶ID成功
const userId = response.data;
setUserId(userId); // 保存用戶id
})
.catch(error => {
// 獲取用戶ID失敗,可能是因為用戶未登錄
console.error('獲取用戶ID失敗:', error.response.data);
// 在這里處理未登錄的情況,比如跳轉(zhuǎn)到登錄頁
});在auth.js中
// 設(shè)置用戶id到 localStorage 中
export function setUserId(userId) {
localStorage.setItem('userid', userId);
}
export function getUserId() {
return localStorage.getItem('userid');
}在需要獲取登錄用戶名的組件中,通過讀取 localStorage 來獲取用戶id。
<template>
<div>
</div>
</template>
<script>
export default {
data() {
return {
userid:'',
};
},
mounted() {
this.user = getUserId('userid');
},
};
</script>總結(jié)
到此這篇關(guān)于前端Vue如何獲取登錄的用戶名或用戶id的文章就介紹到這了,更多相關(guān)Vue獲取登錄用戶名或id內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue中使用create-keyframe-animation與動畫鉤子完成復雜動畫
這篇文章主要介紹了Vue中使用create-keyframe-animation與動畫鉤子完成復雜動畫,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
Vue?調(diào)用攝像頭掃描條碼功能實現(xiàn)代碼
本文介紹了如何使用Vue.js和jsQR庫來實現(xiàn)調(diào)用攝像頭并掃描條碼的功能,通過安裝依賴、獲取攝像頭視頻流、解析條碼等步驟,實現(xiàn)了從開始掃描到停止掃描的完整流程,同時,還強調(diào)了瀏覽器兼容性、HTTPS環(huán)境、權(quán)限問題和性能優(yōu)化的重要性,感興趣的朋友一起看看吧2025-03-03
Ant Design Vue全局對話確認框(confirm)的回調(diào)不觸發(fā)
這篇文章主要介紹了Ant Design Vue全局對話確認框(confirm)的回調(diào)不觸發(fā)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
Element Cascader 級聯(lián)選擇器的使用示例
這篇文章主要介紹了Element Cascader 級聯(lián)選擇器的使用示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07
vue element 中的table動態(tài)渲染實現(xiàn)(動態(tài)表頭)
這篇文章主要介紹了vue element 中的table動態(tài)渲染實現(xiàn)(動態(tài)表頭),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11

