How can I get a result from a POST request into a v-for?

Viewed 56

I have something like this:

<table class="table">
  <tbody>
    <tr v-for="(option, index) in Weapons">
      <td>Primary</td>
      <td>[[ getWeaponType(option.WeaponType) ]]</td>
    </tr>
  </tbody>
</table>

In my Vue object, in methods, I have this:

getWeaponType: function(weaponTypeNumber){
  axios.get('/path/to/api')
  .then(response => {
      return response.data
  })
}

I send an ID and it returns the name for that ID. But I need for it to show in my table whose rows are being generated by the v-for. This isn't working since it is a Promise and the values are not showing. Is there any way I can achieve getting that value to show in the table? I didn't want to do it server side so I'm trying to see if I have any options before I do that.

1 Answers

May I suggest an alternative method?

data() {
  return {
    weaponsMappedWithWeaponTypes: [];
  }
}

mounted() { // I am assuming the weapons array is populated when the component is mounted
  Promise.all(this.weapons.map(weapon => {
    return axios.get(`/path/to/api...${weapon.weaponType}`)
      .then(response => {
          return {
            weapon,
            weaponType: response.data
          }
      })
  ).then((values) => {
    this.weaponsMappedWithWeaponTypes = values
  })
}

computed: {
  weaponsAndTheirWeaponTypes: function () {
    return this.weaponsMappedWithWeaponTypes
  }
}

And then in your template

<table class="table">
  <tbody>
  <tr v-for="(option, index) in weaponsAndTheirWeaponTypes">
      <td>Primary</td>
      <td>option.weaponType</td>
  </tr>
  </tbody>
</table>

Related