首頁  >  問答  >  主體

探索 Vuejs/Laravel 視圖中 async/await 函數的使用

您好,我正在嘗試使用非同步函數從控制器獲取信息,我在組件中執行此操作:

我需要發送參數,因為我已經看到了與 Mounted() 類似的答案,但它們不會向函數發送參數,因此如果我不添加參數,它將無法工作。

查看部分:

<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>

我需要將這兩個參數傳遞給函數:index 1 和 post2.branch_office_id

然後我在方法部分執行此操作:

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() 檢查回應它會得到一個值。 我知道我不能在視圖中使用非同步等待函數,這就是為什麼我使用另一個函數在你可以看到的內部呼叫這個函數,但我不知道為什麼我不直接在視圖中使用它,它說:

$ [object Promise]

所以它沒有顯示值,所以我想知道為什麼?代碼有什麼問題?我真的需要幫助,謝謝!

P粉561438407P粉561438407214 天前415

全部回覆(1)我來回復

  • P粉883973481

    P粉8839734812024-03-20 13:46:48

    您可以使用 data 屬性來儲存回應。然後呼叫函數發出請求,UI 中綁定到資料的任何內容都會相應更新。

    您缺少的部分是 .then(...),它在 fetch 文件。

    例如:

    data: () => ({
      response: null,
    }),
    methods: {
      fetchData() {
        fetch(`/api/collection/total/${day}/${branch_office_id}?api_token=${App.apiToken}`)
        .then(
          (response) => { this.response = response; }
        );
      },
    },

    現在,在您的 UI 中,檢查回應是否已完成返回,v-if="response",然後根據需要顯示它。

    回覆
    0
  • 取消回覆