当 nuxt 中的 props 发生变化时如何更新组件
how to update component when props changes in nuxt
我想每次在组件中的 props 变化时获取数据并在不重新加载页面的情况下显示它。
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>
当我 select/change 开具发票时,我可以看到后端 api 每次都会调用所选发票,但发票数据始终为空白。返回的结果未在 invoiceData
中更新
我认为您需要在 fetchData 方法中使用以下内容
this.invoiceData = invoiceDetails
而不是
return {}
只有已经存在的数据和获取vue/nuxt函数需要return一个对象
我想每次在组件中的 props 变化时获取数据并在不重新加载页面的情况下显示它。
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>
当我 select/change 开具发票时,我可以看到后端 api 每次都会调用所选发票,但发票数据始终为空白。返回的结果未在 invoiceData
中更新我认为您需要在 fetchData 方法中使用以下内容
this.invoiceData = invoiceDetails
而不是
return {}
只有已经存在的数据和获取vue/nuxt函数需要return一个对象