[Vuejs]-What is a good way to call a function that makes an axios request using information from within a v-for?

0👍

This is completely untested however, it should give you a good idea of how to accomplish what you’re after. I have also made a few other changes such as using fat arrow functions and changing to forEach loops instead of basic for loops.

<template>
  <div class="home">
    <h1>{{ message }}</h1>
    <div v-for="order in orders">
      <h2>Order Number:{{ order.id }}</h2>

      <h1 v-for="product in order.carted_products"> <strong>{{ cartedProduct }}</strong> </h1>

      <h3>SUBTOTAL:{{ order.subtotal }}</h3>
      <h3>TAX:{{ order.tax }}</h3>
      <h3>TOTAL: {{ order.total }}</h3>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data: () => ({
    message: "Your Orders",
    orders: [],
    cartedProducts: []
  }),
  mounted: {
    this.doGetOrders()
  },
  methods: {
    doGetOrders: () => {
      axios.get(`/api/order`).then((response) => {
        this.orders = response.data

        this.doCartedProductsInOrder()
      })
    },
    doCartedProductsInOrder: () => {
      if (this.order.length >= 1) {
        this.order.forEach((order) => {
          if (order.cartedProducts >= 1) {
            order.cartedProducts.forEach((product) => {
              this.cartedProducts.push(this.doGetProductInfo(productId))
            })
          }
        })
      }
    },
    doGetProductInfo: (productId) => {
      axios.get(`/api/products/${productId}`).then((response) => {
        if (response.status === 200) {
          return response.data
        }
      })
    }
  }
}
</script>

Leave a comment