Skip to content

登陆人信息获取

1、概述

在我们后台管理项目之中,获取当前登录人信息至关重要,正常我们都会通过在项目之中通过获取当前登录人的ID,偏于对其后续进行对应的操作,比如登录人的头像姓名等的显示,接下来我们就在我们顶部结构部分之中获取登录人的头像等信息。

2、获取用户信息

首先我们登录第一步以后,就是获取用户信息,接下来就在我们的仓库之中先调取我们的用户接口:

用户信息接口就是用token,也就是我们登录以后返回的token,然后通过这个token去获取用户信息。

先完善一下我们的用户信息接口部分的调用:

☞ 用户接口编写

js
// src/api/user.js
import request from '@/utils/request'

export function getInfo(token) {
  return request({
    url: '/user/info',
    method: 'get',
    params: { token }
  })
}

☞ 用户信息接口引入和使用

src/store/modules/user.js

js
import { getInfo } from '@/api/user'
getInfo() {
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        const user = res.user
        const avatar = (user.avatar == '' || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar

        if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          this.roles = res.roles
          this.permissions = res.permissions
        } else {
          this.roles = ['ROLE_DEFAULT']
        }
        this.name = user.userName
        this.avatar = avatar
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

3、思考用户信息的存储

☞ 然后在我们的头部结构部分,调用我们获取用户信息的方法:

每次进入首页,我们都会调用我们的用户信息接口getInfo,获取当前登录人的头像和姓名。

关键点: 这里比较关键的部分就是,我们获取用户信息以后,需要将用户信息保存到我们的store中,这样我们就可以在任何地方调用,那么我们这个方法应该在什么时候调用呢?

第一种思路: 在每次调用接口的时候判断,是否拉取了用户信息

第二种思路: 比较好的一点就是在我们的路由守卫中调用,也就是在每次进入路由之前,我们都会调用这个方法,获取用户信息,然后保存到我们的store中。

第三种思路: 在每次进入页面的时候开始拉取用户的信息

第四种思路: 只有刚进去后台的界面的时候拉取一次用户信息,其他时候不轻易拉取,因为拉取用户信息需要网络请求,如果拉取了,那么就会造成页面卡顿。

☞ 这里拉取的部分也非常简单:

js
// src/store/modules/user.js
import { getInfo } from '@/api/user'
import { useUserStore } from '@/store/modules/user'
useUserStore().getInfo().then(() => {
        
}).catch(err => {
  
})

4、头部拉取用户信息

☞ 接下来我们就在我们后台的菜单头部里面进行拉取我们的用户信息

js
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
onMounted(async () => {
  useUserStore().getInfo().then(() => {
     console.log('userStore', userStore);
  }).catch(err => {
  })
});
</script>

最后效果如下 image.png

5、展示用户信息

接下来我们获取我们的用户信息,然后把登录用户的信息给展示出来

☞ 新建pages => userInfo.vue 用来展示我们的用户信息

☞ 添加对应的路由信息

JS
// 不展示的路由信息
  {
      path: '/profile', // 用户页面
      name: 'profile',
      meta: { title: '用户信息', icon: '<User/>' },
      children: [],
      hidden:false, // 隐藏
      component: () => import('@/pages/profile.vue'),
  },

☞ pages => userInfo.vue 用来展示我们的用户信息

JS
<template>
    <div class="profile">
        <div class="flexhead">
            <span class="kuai"></span>
            <span class="name">用户信息</span>
        </div>
        <div class="module-userinfo">
            <div class="back">
                <div class="imgavatorbox">
                    <img style="width: 100%;" src="/src/assets/images/avator.png" class="imgavator">
                </div>
            </div>
            <div class="back userbox">
                <div class="userli">姓名:{{userStore.name?userStore.name:'--'}}</div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
console.log('userInfo', userStore);
</script>
<style scoped>
/*modelus  st*/
.profile {
    line-height: 20px;
    font-family: PingFangSC, PingFang SC;
}

.flexhead {
    display: flex;
    gap: 10px;
}

.kuai {
    width: 6px;
    height: 20px;
    background: #1890FF;
    border-radius: 8px;
}

/*module-userinfo*/
.module-userinfo {
    background: #FFFFFF;
    border-radius: 10px;
    padding: 10px;
    box-sizing: border-box;
    background: #F2F2F2;
    width: 100%;
    margin-top: 20px;
    display: flex;
    gap: 20px;
}

.module-userinfo .back {
    box-sizing: border-box;
    background: #fff;
    border-radius: 10px;
    display: flex;
    padding: 20px;
}

.module-userinfo .imgavatorbox {
    width: 100px;
    height: 100px;
    border: 1px solid #47A7FF;
    border-radius: 50%;
}

.module-userinfo .imgavator {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
}

.module-userinfo .userbox {
    display: flex;
    flex-wrap: wrap;
    line-height: 30px;
}

.module-userinfo .userli {
    flex: 0 0 50%;
    color: #385C8B;
    min-width: 160px;
}

/*modelus  end*/
</style>

☞ 刷新页面,这个时候我们的页面已经可以成功展示用户的信息!

image.png

6、获取使用存储的用户信息

接下来我们就可以在我们的项目之中开始正常获取我们全局存储的用户信息了。

先来看看我们直接写在状态仓库里面的数据,这部分是如何进行对应的。

JS
 state: () => ({
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  }),

在我们项目之中引入和拿信息也十分简单

JS
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()


// 比如name的取值就是
useUserStore().name=>  userStore.name;

到这里我们直接已经取到了我们想要的name,avatar等数据了,接下来直接去组件之中使用就好了。

Released under the MIT License.