前端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)文章
深入淺析golang zap 日志庫使用(含文件切割、分級別存儲和全局使用等)
這篇文章主要介紹了golang zap 日志庫使用(含文件切割、分級別存儲和全局使用等),本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02Vue 中文本內(nèi)容超出規(guī)定行數(shù)后展開收起的處理的實現(xiàn)方法
這篇文章主要介紹了Vue 中文本內(nèi)容超出規(guī)定行數(shù)后展開收起的處理的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04vue 項目集成 electron 和 electron 打包及環(huán)境配
文章介紹了如何使用Vue和Electron開發(fā)桌面端應(yīng)用,包括安裝Electron、配置package.json、創(chuàng)建main.js文件、運行和打包應(yīng)用等步驟,并分享了一些常見的打包錯誤及其解決方法,感興趣的朋友一起看看吧2025-01-01