【问题标题】:How to pass dynamic parameter (ID) to axios api call?如何将动态参数(ID)传递给 axios api 调用?
【发布时间】:2020-01-11 00:33:14
【问题描述】:

我有一个最后一部分是动态的 api: src/api/user.js

export function getProfileData() {
  return request({
    url: 'http://localhost:8000/profile_update/DYNAMIC USER ID HERE',
    method: 'get',
  })
}

我在这个动作中调用这个 api: 存储/模块/user.js

setProfileData({ commit }) {
 return getProfileData(userId).then(response => {
 console.log('RESPONSE setProfileData action dispatch', response)
 commit('SET_PROFILE_DATA', response.results)
})

(在这个模块中我也有状态和突变 - 工作) 此操作在此处发送: src/views/users-list

goToUserProfile(user) {
  const userId = user.id
  this.$store.dispatch('user/setCurrentUser').then(() => {
    const profileData = 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 fetchin' userDataProfile: ', err)
     this.loading = false
   })
 })
}

参数用户来自于

@click.prevent="goToUserProfile(data.item), selectUser(data.item)"

所以 data.item = 单个选定用户

此代码不起作用。 我需要在 api 中使用动态用户 ID。 在店里我也有:

setCurrentUser({ commit }, userData) {
commit('SET_CURRENT_USER', userData)}

运行良好 - 在 userData 内部有属性 id。

我尝试使用 /${params.userId},但如何在 api 中传递它?

如何将 userId 传递给 axios 调用? 希望我已经清楚了。 我已经提取了很多代码,所以如果需要我会全部发布。

【问题讨论】:

    标签: vuejs2 axios vue-router store dynamic-url


    【解决方案1】:
    • getProfileData函数getProfileData(usedId)添加id参数并将其包含在url中: url: http://localhost:8000/profile_update/${ DYNAMIC USER ID HERE }(记得把链接用反引号括起来)
    • setProfileData函数添加id参数:setProfileData({ commit }, userId)
    • 如果 id 将是路由参数,请使用 this.$route.params.userId 提取它

    希望这会有所帮助。

    对整个 url 使用 backtips 而不是双引号,这样就可以了。

    【讨论】:

    • 我尝试过这种方式,但是当我将 userId 设置为操作中的参数时,它保持灰色。如何相应地更新它?我试过setProfileData({ commit }, userId) { return getProfileData(userId).then(response => { console.log('RESPONSE setProfileData action dispatch', response) commit('SET_PROFILE_DATA', response.results) }) },,但请求不是动态的(读起来像这样:'localhost:8000/profile_update/$%7Bparams.userId%7D'
    • 另外,在控制台中:未知操作类型:user/setProfileData(userId)。
    • 您是否将 url 包含在反引号中?另外,如果你已经将用户模块添加到主存储文件,你可以直接引用它setProfileData(userId)而不是user/setProfileData(userId)提示:在setProfileData内,在return语句之前将userId打印到控制台以验证它的价值。
    • 反引号应该包含整个 url 还是只包含动态部分?在export function getProfileData(userId) { return request({ url: 'http://localhost:8000/profile_update/`${params.userId}`', method: 'get', }) } 中,参数 userId 保持灰色。并且仍然未知动作类型,即使上面的动作(以相同的方式编写 - /user/ )没有显示错误。
    • 用反引号而不是引号包裹整个网址。
    猜你喜欢
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2019-08-06
    • 2018-08-15
    • 2013-06-04
    • 1970-01-01
    相关资源
    最近更新 更多