前端Vue怎么获取登录的用户名或用户id

一、使用全局状态管理(Vuex)获取登录用户名

创建 Vuex store,并在其中定义一个用于存储用户名的状态。

javascript 复制代码
// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    username: '', // 存储登录用户名的状态
    userid:'',//储存登录用户id
  },
  mutations: {
    setUsername(state, username) {
      state.username = username;
    },
    setUserid(state, userid) {
      state.userid = userid;
    },
  },
});

在登录成功后,将用户名保存到 Vuex store 中。

javascript 复制代码
// 登录成功后的处理
this.$store.commit('setUsername', username);
this.$store.commit('setUserid', userid);

在需要获取登录用户名的组件中,使用计算属性来获取用户名。

javascript 复制代码
<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是我写的后端接口函数,SetUserId将用户id保存到 localStorage 中。

javascript 复制代码
    getUserid()
      .then(response => {
     // 获取用户ID成功
       const userId = response.data;
      setUserId(userId); // 保存用户id
  })
      .catch(error => {
       // 获取用户ID失败,可能是因为用户未登录
      console.error('获取用户ID失败:', error.response.data);
    // 在这里处理未登录的情况,比如跳转到登录页
  });

在auth.js中

javascript 复制代码
// 设置用户id到 localStorage 中
export function setUserId(userId) {
  localStorage.setItem('userid', userId);
}
export function getUserId() {
  return localStorage.getItem('userid');
}

在需要获取登录用户名的组件中,通过读取 localStorage 来获取用户id。

javascript 复制代码
<template>
  <div>

  </div>
</template>

<script>
export default {
  data() {
    return {

      userid:'',
    };
  },
  mounted() {

    this.user = getUserId('userid');

  },
};
</script>
相关推荐
万少31 分钟前
HarmonyOS官方模板集成创新活动-流蓝卡片
前端·harmonyos
-To be number.wan3 小时前
C++ 赋值运算符重载:深拷贝 vs 浅拷贝的生死线!
前端·c++
噢,我明白了3 小时前
JavaScript 中处理时间格式的核心方式
前端·javascript
纸上的彩虹4 小时前
半年一百个页面,重构系统也重构了我对前端工作的理解
前端·程序员·架构
be or not to be5 小时前
深入理解 CSS 浮动布局(float)
前端·css
LYFlied5 小时前
【每日算法】LeetCode 1143. 最长公共子序列
前端·算法·leetcode·职场和发展·动态规划
老华带你飞5 小时前
农产品销售管理|基于java + vue农产品销售管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
小徐_23335 小时前
2025 前端开源三年,npm 发包卡我半天
前端·npm·github
C_心欲无痕5 小时前
vue3 - 类与样式的绑定
javascript·vue.js·vue3
GIS之路6 小时前
GIS 数据转换:使用 GDAL 将 Shp 转换为 GeoJSON 数据
前端