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

如何向Axios API请求传递动态用户ID参数?

解决动态用户ID传入Axios API请求的问题

咱们先梳理下现有代码里的几个关键问题,然后一步步调整就能搞定这个动态参数传递的问题:

1. 让API函数支持接收动态userId参数

你当前的getProfileData函数没有接收参数的入口,首先要修改它,让它能接收userId并拼接到请求URL中:

// src/api/user.js
export function getProfileData(userId) { // 新增userId参数
  return request({
    // 使用模板字符串拼接动态ID
    url: `http://localhost:8000/profile_update/${userId}`,
    method: 'get',
  })
}

2. 调整Vuex Action,传递userId给API

你的setProfileData action目前没有接收userId参数的逻辑,需要修改它的参数结构(Vuex action的第二个参数就是外部传入的payload):

// store/modules/user.js
setProfileData({ commit }, userId) { // 新增userId作为第二个参数
  return getProfileData(userId).then(response => {
    console.log('RESPONSE setProfileData action dispatch', response)
    commit('SET_PROFILE_DATA', response.results)
  })
}

3. 修正组件中dispatch的调用方式

你在goToUserProfile里的dispatch写法有语法错误,而且setCurrentUser也需要传入选中的user数据(因为它的定义是接收userData参数),调整如下:

// src/views/users-list
goToUserProfile(user) {
  const userId = user.id
  // 调用setCurrentUser时传入选中的user数据
  this.$store.dispatch('user/setCurrentUser', user).then(() => {
    // 正确传递userId给setProfileData,注意dispatch的第二个参数才是payload
    this.$store.dispatch('user/setProfileData', userId).then(() => {
      const profileData = this.$store.getters.profileData
      this.profileData = profileData
      console.log('users-list sending profile data: ', profileData )
      this.$router.push({ name: 'SeeUserProfile', params: { userId: userId } })
    }).catch((err) => {
      console.log('ERROR IN fetching userDataProfile: ', err)
      this.loading = false
    })
  })
}

额外优化(可选)

既然你已经把当前用户存在Vuex的state里了,也可以直接从state中获取userId,不用每次手动传递:

// store/modules/user.js
setProfileData({ commit, state }) { // 解构出state
  const userId = state.currentUser.id // 从state取当前用户ID
  return getProfileData(userId).then(response => {
    console.log('RESPONSE setProfileData action dispatch', response)
    commit('SET_PROFILE_DATA', response.results)
  })
}

这样组件里的dispatch就不用传userId了,直接调用this.$store.dispatch('user/setProfileData')即可,代码会更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:35:45