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


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

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

    1. // store.js
    2. import Vue from 'vue';
    3. import Vuex from 'vuex';
    4. Vue.use(Vuex);
    5. export default new Vuex.Store({
    6. state: {
    7. username: '', // 存储登录用户名的状态
    8. userid:'',//储存登录用户id
    9. },
    10. mutations: {
    11. setUsername(state, username) {
    12. state.username = username;
    13. },
    14. setUserid(state, userid) {
    15. state.userid = userid;
    16. },
    17. },
    18. });

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

    1. // 登录成功后的处理
    2. this.$store.commit('setUsername', username);
    3. this.$store.commit('setUserid', userid);

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

    1. <script>
    2. export default {
    3. computed: {
    4. username() {
    5. return this.$store.state.username;
    6. },
    7. userid() {
    8. return this.$store.state.userid;
    9. },
    10. },
    11. };
    12. script>

    二、使用浏览器本地存储(localStorage)获取登录用户id

    1.在登录成功后getUserid是我写的后端接口函数,SetUserId将用户id保存到 localStorage 中。

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

    在auth.js中

    1. // 设置用户id到 localStorage 中
    2. export function setUserId(userId) {
    3. localStorage.setItem('userid', userId);
    4. }
    5. export function getUserId() {
    6. return localStorage.getItem('userid');
    7. }

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

    1. <script>
    2. export default {
    3. data() {
    4. return {
    5. userid:'',
    6. };
    7. },
    8. mounted() {
    9. this.user = getUserId('userid');
    10. },
    11. };
    12. script>

  • 相关阅读:
    Redis面试题一(基本概念)
    Spring Boot 国际化踩坑指南
    cmd基本命令
    关于数据库优化你知道多少?
    IJ中配置TortoiseSVN插件:
    Python sort 自定义函数排序
    ubuntu从源码编译gdal
    基于虚拟机的集群冗余简化
    Python Whois 信息扫描
    第53篇-某天猫评论sign参数分析【2022-08-31】
  • 原文地址:https://blog.csdn.net/zyhang666/article/details/138678187