問題
項目中遇到一個需求,在填寫商品的時候,選擇商品分類后,加載出商品分類的擴展屬性。
這個擴展屬性有可能是自定義的數據字典里的單選/多遠。
要用第一個axios查詢擴展屬性,第二個axios 從第一個axios中獲得的code值去查詢 數據字典。
解決思路
我是net后端開發,之前沒有接觸過Vue,也沒用過axios,以前使用ajax是 直接加async:false屬性就能同步執行。
在axios中沒有這個屬性,經過一番查找,發現可以使用ES8新特性 async/await 解決,類似於c#的異步,用法差不多。
具體的用法是 在需要實現同步的方法前面+async 使用方法的時候前面+ await。
然而我發現這樣寫第一個axios async是失效的,如下圖所示,百思不得其解。
詢問前端大佬才發現這個函數是一個匿名函數,真正需要等待的是then后面的函數,async需要加在then后面。修改后,問題解決。
示例代碼
第一個axios:
// async callApiWithPost('/Owner_Manage/Goods_Extend/GetAllExtendBySortIds', this.groupIds).then((resJson) => {
callApiWithPost('/Owner_Manage/Goods_Extend/GetAllExtendBySortIds', this.groupIds).then(async(resJson) => { if (resJson.Data !== null && resJson.Data.length > 0) { for (var index = 0; index < resJson.Data.length; index++) { let codeList = [] // 如果擴展屬性 Type = 4 || 5 ,則執行同步axios方法,查找該擴展屬性的字典項,加載到tableData中 if (resJson.Data[index].Type === 4 || resJson.Data[index].Type === 5) { codeList = await this.$options.methods.getCodeList(resJson.Data[index].Code) } this.$refs.tableValue.tableData.push({ ExtendId: resJson.Data[index].Id, Name: resJson.Data[index].Name, Type: resJson.Data[index].Type, codeList: codeList }) } } }).catch((e) => { console.log('獲取分類數據失敗') })
第二個axios:
async getCodeList(code) { const codeList = [] await callApiWithPost('/BaseInfo_Manage/Base_Code/GetCodeListByType', { id: code.trim() }) .then((resJson) => { if (!resJson.Data || Object.keys(resJson.Data).length === 0) { this.$message.error('未查詢到數據或數據為空') } else { for (var m = 0; m < resJson.Data.length; m++) { codeList.push({ id: resJson.Data[m].Id, name: resJson.Data[m].Name }) } } }).catch((e) => { console.log('獲取字典項數據失敗') }) return codeList },