您好,我正在嘗試使用非同步函數(shù)從控制器獲取信息,我在組件中執(zhí)行此操作:
我需要發(fā)送參數(shù),因為我已經(jīng)看到了與 Mounted() 類似的答案,但它們不會向函數(shù)發(fā)送參數(shù),因此如果我不添加參數(shù),它將無法工作。
查看部分:
<tbody> <tr v-for="(post, index) in last_month_day" v-bind:index="index"> <td>{{ index 1 }}</td> <td v-for="(post2, index2) in branch_office_posts" v-bind:index="index2"> $ {{ getTotalIncomes(index 1, post2.branch_office_id) }} </td> </tr> </tbody>
我需要將這兩個參數(shù)傳遞給函數(shù):index 1 和 post2.branch_office_id
然後我在方法部分執(zhí)行此操作:
methods: { async TotalIncomeData(day, branch_office_id) { const response = await fetch('/api/collection/total/' day '/' branch_office_id '?api_token=' App.apiToken) return response; }, getTotalIncomes(day, branch_office_id) { return this.TotalIncomeData(day, branch_office_id); },
它有效,我的意思是如果使用 console.log() 檢查回應(yīng)它會得到一個值。 我知道我不能在視圖中使用非同步等待函數(shù),這就是為什麼我使用另一個函數(shù)在你可以看到的內(nèi)部呼叫這個函數(shù),但我不知道為什麼我不直接在視圖中使用它,它說:
$ [object Promise]
所以它沒有顯示值,所以我想知道為什麼?代碼有什麼問題?我真的需要幫助,謝謝!
您可以使用 data
屬性來儲存回應(yīng)。然後呼叫函數(shù)發(fā)出請求,UI 中綁定到資料的任何內(nèi)容都會相應(yīng)更新。
您缺少的部分是 .then(...)
,它在 fetch
文件。
例如:
data: () => ({ response: null, }), methods: { fetchData() { fetch(`/api/collection/total/${day}/${branch_office_id}?api_token=${App.apiToken}`) .then( (response) => { this.response = response; } ); }, },
現(xiàn)在,在您的 UI 中,檢查回應(yīng)是否已完成返回,v-if="response"
,然後根據(jù)需要顯示它。