编辑 | blame | 历史 | 原始文档

首页用户ID获取问题修复说明

问题描述

在首页点击"绑定车辆"按钮时,调用接口 /system/vehicle/user/bound/undefined,导致 userIdundefined,无法正确获取用户绑定的车辆信息。

问题分析

错误原因

pages/index.vue 中:

  1. 缺少 currentUser 计算属性
    javascript computed: { ...mapState({ userName: state => state.user.name // ❌ 缺少 currentUser 映射 }) }

  2. 错误使用 currentUser.userId
    javascript loadRunningTasks() { const queryParams = { assigneeId: this.currentUser.userId, // ❌ currentUser 未定义 } }

错误影响范围

  1. 已执行但有问题的功能
  • loadUserProfile() - 调用 getUserProfile API(不需要 userId 参数)✅ 正常
  • loadRunningTasks() - 使用 this.currentUser.userId ❌ 报错
  1. 受影响的接口调用
  • 获取绑定车辆信息时,间接受影响(因为依赖用户登录状态)
  • 加载任务列表时,无法获取正确的 assigneeId

解决方案

修改文件

文件路径app/pages/index.vue

具体修改

1. 添加 currentUser 计算属性

修改前:
javascript computed: { ...mapState({ userName: state => state.user.name }), // ... 其他计算属性 }

修改后:
javascript computed: { ...mapState({ userName: state => state.user.name, currentUser: state => state.user // ✅ 添加 currentUser 映射 }), // ... 其他计算属性 }

2. 优化 loadUserProfile() 方法

修改前:
javascript loadUserProfile() { getUserProfile().then(response => { const userInfo = response.data || response if (userInfo.boundVehicle) { this.boundVehicle = userInfo.boundVehicle.vehicleNumber this.boundVehicleId = userInfo.boundVehicle.vehicleId } }).catch(error => { console.error('获取用户信息失败:', error) }) }

修改后:
```javascript
loadUserProfile() {
const userId = this.currentUser.userId
if (!userId) {
console.error('用户未登录,无法获取绑定车辆信息')
return
}

getUserProfile().then(response => {
const userInfo = response.data || response
if (userInfo.boundVehicle) {
this.boundVehicle = userInfo.boundVehicle.vehicleNumber
this.boundVehicleId = userInfo.boundVehicle.vehicleId
}
}).catch(error => {
console.error('获取用户信息失败:', error)
})
}
```

改进点:
- ✅ 添加用户登录状态检查
- ✅ 提前返回,避免无效的 API 调用

3. 优化 loadRunningTasks() 方法

修改前:
javascript loadRunningTasks() { this.loading = true const queryParams = { pageNum: 1, pageSize: 100, assigneeId: this.currentUser.userId, // ❌ currentUser 未定义 taskStatuses: 'PENDING,DEPARTING,ARRIVED,RETURNING,IN_PROGRESS' } // ... }

修改后:
```javascript
loadRunningTasks() {
const userId = this.currentUser.userId
if (!userId) {
console.error('用户未登录,无法加载任务列表')
return
}

this.loading = true
const queryParams = {
pageNum: 1,
pageSize: 100,
assigneeId: userId, // ✅ 使用已验证的 userId
taskStatuses: 'PENDING,DEPARTING,ARRIVED,RETURNING,IN_PROGRESS'
}
// ...
}
```

改进点:
- ✅ 提取 userId 到独立变量
- ✅ 添加用户登录状态检查
- ✅ 提前返回,避免无效的 API 调用
- ✅ 代码更清晰易读

Vuex 状态管理

state.user 数据结构

根据项目中的 Vuex 配置,state.user 包含以下信息:

{
  userId: 1,              // 用户ID
  name: '张三',           // 用户名
  avatar: '',             // 头像
  deptId: 101,            // 部门ID
  roles: [],              // 角色列表
  permissions: []         // 权限列表
}

正确使用方式

方式1:通过 mapState 映射整个 user 对象

computed: {
  ...mapState({
    currentUser: state => state.user
  })
}

// 使用时:
this.currentUser.userId
this.currentUser.name
this.currentUser.deptId

方式2:通过 mapState 映射单个属性

computed: {
  ...mapState({
    userId: state => state.user.userId,
    userName: state => state.user.name,
    userDeptId: state => state.user.deptId
  })
}

// 使用时:
this.userId
this.userName
this.userDeptId

推荐方式1,因为:
- ✅ 代码更简洁
- ✅ 易于扩展(需要新属性时不用修改 computed)
- ✅ 与其他页面保持一致(如 bind-vehicle.vue

参考实现

bind-vehicle.vue 的正确实现

bind-vehicle.vue 中使用了相同的模式:

computed: {
  ...mapState({
    currentUser: state => state.user
  })
},

methods: {
  loadCurrentBoundVehicle() {
    const userId = this.currentUser.userId
    getUserBoundVehicle(userId).then(response => {
      // ...
    })
  }
}

这是本次修复的参考标准。

测试验证

功能测试

  1. 用户登录状态
  • ✅ 已登录:正常显示用户名和绑定车辆信息
  • ✅ 未登录:控制台输出错误信息,不发起 API 请求
  1. 绑定车辆功能
  • ✅ 点击"绑定车辆"按钮,正确跳转到绑定页面
  • ✅ 绑定成功后返回首页,显示更新后的车辆信息
  1. 任务列表加载
  • ✅ 正确加载当前用户的任务列表
  • ✅ assigneeId 参数正确传递

API 调用验证

修复前:
GET /system/vehicle/user/bound/undefined ❌ 错误

修复后:
GET /system/vehicle/user/bound/1 ✅ 正确

预防措施

1. 统一 Vuex 使用规范

在所有页面中,需要使用用户信息时,统一采用以下方式:

export default {
  computed: {
    ...mapState({
      currentUser: state => state.user
    })
  },
  
  methods: {
    someMethod() {
      const userId = this.currentUser.userId
      if (!userId) {
        console.error('用户未登录')
        return
      }
      // 继续业务逻辑
    }
  }
}

2. 添加用户登录检查

在所有需要用户信息的方法中,添加登录状态检查:

const userId = this.currentUser.userId
if (!userId) {
  console.error('用户未登录,无法执行操作')
  return
}

3. 使用 ESLint 规则

可以添加 ESLint 规则检测未定义的变量:

{
  "rules": {
    "no-undef": "error",
    "no-unused-vars": "warn"
  }
}

相关文件

本次修改涉及的文件

相关参考文件

相关文档

总结

本次修复通过以下步骤解决了 userId 为 undefined 的问题:

  1. ✅ 在 computed 中添加 currentUser 映射
  2. ✅ 在 loadUserProfile() 中添加用户登录检查
  3. ✅ 在 loadRunningTasks() 中提取并验证 userId
  4. ✅ 统一使用 this.currentUser.userId 获取用户ID

核心改进
- 代码更健壮,增加了错误检查
- 遵循了项目中其他页面的最佳实践
- 避免了无效的 API 调用
- 提供了更好的错误提示

版本历史

版本 日期 修改内容 修改人

| 1.0 | 2025-10-15 | 修复 userId 为 undefined 的问题 | - |