亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

前端Vue如何獲取登錄的用戶名或用戶id代碼實(shí)例

 更新時間:2024年07月05日 09:31:11   作者:幾行名姓  
在前端開發(fā)中,獲取登錄用戶的用戶名是一項(xiàng)常見的需求,這篇文章主要給大家介紹了關(guān)于前端Vue如何獲取登錄的用戶名或用戶id的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

一、使用全局狀態(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失敗,可能是因?yàn)橛脩粑吹卿?
      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)文章

最新評論