how to update component when props changes in nuxt

I want to fetch data everytime when props changes in component and display it without reloading page.

this pages/invoice/index.vue

<template>
<div>
 <b-table-column
     field="InvoiceNo"
     label="Invoice No"
     sortable
     v-slot="props"
     >
      <a @click="selectInvoice(props.row.id)">
         {{ props.row.invoiceNumber }}
      </a>
 </b-table-column>
<Invoice :invoiceId="selectedInvoice" />
</div>
</template>

<script>
import axios from "axios";
import Invoice from "../../../components/Invoice.vue";
export default {
  components: {
    Invoice,
  },
  data() {
    return {
      selectedInvoice: "",
   }
  },
methods: {
   selectInvoice(invoiceId) {
    this.selectedInvoice = invoiceId;
   },
}

}

</script>

this is components/Invoice.vue

    <script>
import axios from "axios";
export default {
  props: ["invoiceId"],
  data() {
    return {
      invoiceData: "",
    };
  },

  watch: {
    invoiceId: function (newVal, oldVal) {
      this.fetchData(newVal)
    },
    deep: true,
    immediate: true,
  },

  methods: {
    async fetchData(invoiceId) {
      let { data: invoiceDetails } = await axios.get(
        `${process.env.backendapi}/invoice/byid?invoiceId=${invoiceId}`
      );
      return {
        invoiceData: invoiceDetails,
      };
    },
  },
};
</script>

when i select/change invoice, i can see backend api getting called everytime with selected invoice, but invoiceData is always blank. returned result is not getting updated in invoiceData

>Solution :

I think you want the following in the fetchData method

this.invoiceData = invoiceDetails

Instead of

return {}

Only the already existing data and fetch vue/nuxt functions need to return an object

Leave a Reply