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

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

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

// 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 中。

// 登录成功后的处理
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是我写的后端接口函数,SetUserId将用户id保存到 localStorage 中。

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

在auth.js中

// 设置用户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>

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

几行名姓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值