接收api的方式 - daniel-qa/Vue GitHub Wiki

接收api的方式

1 .基礎 Promise 寫法:

函式後面加 .then( 接收值 )

this.getTeacherCount(serviceId).then(count => {
    this.assignedTeacherCount = count;
});

ex2

this.getQuotaData().then(res => {
  this.quotaData = res;
  console.log('配額授權資料載入完成:', res)
})
// 取得HiTeach 配額授權資料 (service,Teachers)
getQuotaData() {
    return new Promise((resolve, reject) => {

        // 使用固定參數取得全部授權資料
        const params = {
            schoolId: this.$store.state.userInfo?.schoolCode, // 使用系統固定的學校ID
            prodCode: 'xxxxxx'           // 固定產品代碼
        }

        // 使用 API 獲取教師配額及空間一覽
        this.$api.serviceDriveAuth.getTeachersQuota(params).then(
            res => {
                resolve(res)
            }
        ).catch(err => {
            console.error('獲取授權一覽名單失敗:', err)
            this.$Message.error('獲取授權一覽名單失敗')
            reject(err)
        }).finally(() => {
            //this.isLoading = false
        })
    })
},

resolve(res) 的作用是將 API 請求回傳的資料 (res) 傳遞出去,讓外面調用這個函式的 .then() 區塊能夠接收到這些資料並進行後續處理。

resolve(res) 沒有「回傳」實際的資料,它是把資料傳遞出去。這是一個重要的區別。

this.getQuotaData().then(data => {
  // 這裡的 data 才是實際的資料
  this.quotaData = data
})

2 .使用 async/await 寫法(更簡潔):

直接用 await, 在函式前面加上 await

async updateHiTeachQuotaProduct() {
    // ... 其他代碼 ...
    if (serviceId) {
        this.assignedTeacherCount = await this.getTeacherCount(serviceId);
    }
}

3. 如果需要錯誤處理:

// 使用 .catch()
this.getTeacherCount(serviceId)
    .then(count => {
        this.assignedTeacherCount = count;
    })
    .catch(error => {
        console.error('發生錯誤:', error);
    });

// 或使用 async/await 的 try/catch
async updateHiTeachQuotaProduct() {
    try {
        if (serviceId) {
            this.assignedTeacherCount = await this.getTeacherCount(serviceId);
        }
    } catch (error) {
        console.error('發生錯誤:', error);
    }
}

建議使用 async/await 寫法,因為它更簡潔易讀,特別是在處理多個異步操作時。