You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js结合Axios获取登录用户信息的占位代码替换咨询

两处占位符的替换方案

前置准备

  • 确保后端已提供获取当前登录用户信息的接口,示例接口地址为/api/user/current,你可以替换为自己项目的实际接口地址
  • 确保axios已安装并完成基础配置,若未全局挂载,需要在对应文件顶部添加import axios from 'axios'
  • 确保请求会自动携带登录身份凭证(如token、cookie等),如果axios未全局配置withCredentials: true,需要在请求中单独添加

1. write get request with axios to api 替换内容

统一替换为axios的get请求写法,示例:
axios.get('/api/user/current', { withCredentials: true })
如果axios已经全局配置了baseURL和凭证携带规则,可以简化为:
axios.get('/user/current')

2. object from res 替换内容

通常后端接口会将业务数据放在响应体的data字段中,所以直接替换为:
res.data
如果你的后端接口是将用户信息直接放在响应体根节点,可替换为res


替换后的完整代码示例

(1)ProfileDropDown.vue 替换后代码

<template>
  <div class="text-right leading-tight hidden sm:block">
    <p class="font-semibold">{{ activeUserInfo.displayName }}</p>
    <small>Available</small>
  </div>
</template>

<script>
import axios from 'axios' // 若已全局挂载可删除此行
export default {
  data () {
    return {
       activeUserInfo: {} // 改为空对象避免初始化取值报错
    }
  },
  methods: {
    async getUserInfo () {
      try {
           const res = await axios.get('/api/user/current', { withCredentials: true })
           this.activeUserInfo = res.data
      } catch (e) {
        // 可在此处添加错误处理逻辑,如获取失败跳转登录页
        console.error('用户信息获取失败', e)
      }
    }
  },
  async created() {
     await this.getUserInfo();
  }
}
</script>

(2)state.js 状态管理代码替换后

注意原代码的getUserInfo函数需要添加async关键字,否则无法使用await:

import axios from 'axios' // 若已全局挂载可删除此行
// ...
const getUserInfo = async () => {
  let userInfo = {}
  try {
      const res = await axios.get('/api/user/current', { withCredentials: true })
      userInfo = res.data
  } catch (e) {
    console.error('用户信息获取失败', e)
  }
  return userInfo
}
// ...

额外注意事项

  • 接口返回的用户信息对象需要包含displayName字段,否则模板渲染会报错,你可以根据实际返回的字段名调整模板中的取值

内容的提问来源于stack exchange,提问作者msh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 03:18:04