如何解决Vue3 基于父级传递的异步 prop 获取数据的最佳方式
在 Vue 3 中,我的组件“App”发出异步 API 请求以检索有关“购买”的信息。这个“购买”被传递给它的子组件“DeliveryInfo”。
在“DeliveryInfo”中,我需要根据“purchase”道具中包含的“customerId”属性发出另一个请求。但是,当“DeliveryInfo”收到“purchase”道具时,它的值起初是未定义的。然后第二个 API 请求将失败。
为了避免这种情况,我使用了一个观察者,这样当“DeliveryInfo”最终获得“purchase”道具的内容时,它会调用 API 并更新自己的数据。
我听说这对性能不利。有人可以帮我改进我的代码吗?
这是我的 App.vue 组件:
<template>
<Purchase :purchase="purchase" />
</template>
<script>
import Purchase from "./components/Purchase"
export default {
name: "App",components: { Purchase },data() {
return {
purchase: []
};
},methods: {
async fetchPurchase(id) {
const response = await fetch(`myapi.com/purchases/${id}`);
const data = await response.json();
return data;
}
},async created() {
// example with a specific id
this.purchase = await this.fetchPurchase(79886);
}
}
</script>
还有我的 DeliveryInfo 组件:
<template>
<div class="delivery-info embossed">
<div>
<h4>Adress</h4>
<p>{{ purchase.deliveryAdress }}</p>
<p>{{ purchase.deliveryCity }}</p>
</div>
<div>
<h4>Customer info</h4>
<p>{{ customerData.firstname }} {{customerData.lastname}}</p>
<p>{{ customerData.phone }}</p>
</div>
</div>
</template>
<script>
export default {
name: "DeliveryInfo",props: ["purchase"],data(){
return{
customerData: {}
}
},methods:{
async fetchCustomer(){
if(!this.purchase){
return
}
const response = await fetch(`myapi/customers/${this.purchase.customerId}`)
this.customerData = await response.json()
}
},watch : {
purchase(){
this.fetchCustomer()
}
}
}
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。