Home > other >  How can I return a value with a function and axios Vuejs
How can I return a value with a function and axios Vuejs

Time:04-21

    getTotalIncomes(day, branch_office_id) {
            axios.post('/api/collection/total/' day '/' branch_office_id '?api_token=' App.apiToken)
            .then(response => {
                return response.data; 
            })
            .catch(function (error) {
                console.log(error);
            });
        }

If I add the return like that, it does not return anything... my view is like this:

      <td v-for="(post2, index2) in branch_office_posts" v-bind:index="index2">
           $ {{ getTotalIncomes(20, 2) }}
      </td>

It should return me a value.. but it returns blank.. so I wonder how can I return the value from the function? Thanks

CodePudding user response:

Two things are needed:

  1. return the promise produced by axios...
return axios.post('/api/collection/...
  1. Place the result in data and refer to that data in the markup...

Markup (refer to the array of results corresponding to the index):

<td v-for="(post2, index2) in branch_office_posts" v-bind:index="index2">
  $ {{ totalIncomes[index2] }}
</td>

Code (call the api with Promise.all over each of the inputs)

  data: function () {
    return {
      totalIncomes: []
    }
  },

  mounted() {
    // or anytime after mounted...
    // call whichever object owns getTotalIncomes method (assumed to be "this" here)
    const promises = this.branch_office_posts.map(b => {
      const params = // some function of b
      return this.getTotalIncomes(params);
    })
    Promise.all(promises)
      .then(result => this.totalIncomes = result);  // update data
  }

CodePudding user response:

This is not possible. Fetch the data, save in reactive variable and bind it to the template.

  • Related