我有一个显示共同基金列表的页面。对于每个共同基金,我都有一个按钮来显示他们的资产净值历史。此按钮调用具有嵌入式 API 调用的组件以获取 NAV 历史记录。我将要为其获取数据的基金代码作为道具传递给组件。但是,当调用 prop 时,我无法自动触发 API 调用。
这是我现在的代码:
父组件(主页):
<template>
<!-- some code -->
<a href="#" @click="fetchNavHistory(fund)">
<v-icon small>history</v-icon>
</a>
<!-- some more code -->
<NAVHistory
:show="showNavHistory"
:amfi_code="amfi_code"
ref="history"
@hide="showNavHistory=false"
/>
</template>
export default {
name: "FundList",
components: {
NAVHistory
},
data() {
return {
showNavHistory: false,
amfi_code: 0
}
},
methods:{
fetchNavHistory(fund){
this.amfi_code = fund.amfi_code
this.showNavHistory = true
var child = this.$refs.history
child.fetchNavHistory()
}
}
}
子组件(显示 NAV 历史记录的地方):
<template>
<!-- some code -->
</template>
<script>
export default {
props: {
show: Boolean,
amfi_code: Number
},
data(){
return{
apiURL: process.env.VUE_APP_BASEURL,
navHistory: [],
}
},
methods: {
async fetchNavHistory(){
try{
const response = await fetch(this.apiURL + '/navhistory', {
method: 'POST',
body: JSON.stringify({"amfi_code": this.amfi_code}),
headers: {'content-type': 'application/json; charset=UTF-8'},
})
const data = await response.json()
console.log(data)
this.navHistory = data
} catch(error){
console.log(error)
}
}
}
}
</script>
起初我尝试在事件上调用该fetchNavHistory()方法。updated()但是当组件显示在屏幕上时,它会不停地调用 API。
然后我尝试watch为show道具添加一个。但这根本不起作用。
最后,作为一种解决方法,我从父组件本身调用 API。当它工作时,它使用 amfi_code 的先前值调用组件,而不是更新的值。所以第一次调用时,amfi_code 被作为 0 传递。
有没有办法在组件显示时安全触发 API 调用,即showprop 设置为 true?