在Vue3中處理異步API調(diào)用并更新表單數(shù)據(jù)的方法示例
前言
從實戰(zhàn)問題中剖析知識點
1. 問題所示
執(zhí)行Vue3數(shù)據(jù)的時候,終端輸出的data如下所示
Promise {<pending>} [[Prototype]] : Promise [[PromiseState]] : "fulfilled" [[PromiseResult]] : Array(13)
截圖如下所示:
2. 知識分析
輸出的數(shù)據(jù)是JavaScript的Promise對象的
對于這個數(shù)據(jù)基本的數(shù)據(jù)分析如下:
Promise {<pending>}
:Promise對象的初始狀態(tài),處于等待狀態(tài)[[Prototype]]: Promise
:對象的原型鏈,通過Promise構(gòu)造函數(shù)創(chuàng)建的[[PromiseState]]: "fulfilled"
:Promise對象的內(nèi)部狀態(tài),已經(jīng)成功完成[[PromiseResult]]: Array(13)
:對象的結(jié)果
對于Promise的狀態(tài)有如下:
- Pending(待定):Promise剛創(chuàng)建時的初始狀態(tài)
- Fulfilled(成功):操作成功完成,Promise有了結(jié)果
- Rejected(失敗):操作失敗,Promise有了失敗的原因
Promise的結(jié)果:當(dāng)Promise狀態(tài)變?yōu)閒ulfilled時,會有一個對應(yīng)的結(jié)果值,這里是一個包含13個元素的數(shù)組
正確處理Promise的結(jié)果,例如使用.then()
和.catch()
方法
比如查看輸出內(nèi)容:
myPromise.then(result => console.log(result));
做適當(dāng)?shù)腻e誤處理:
myPromise .then(result => { console.log(result); }) .catch(error => { console.error('Error:', error); });
給個示例Demo:
function fetchData() { return new Promise((resolve, reject) => { // 模擬異步操作 setTimeout(() => { const data = Array(13).fill('example data'); resolve(data); }, 1000); }); } // 使用Promise fetchData() .then(result => { console.log('Promise fulfilled with result:', result); }) .catch(error => { console.error('Promise rejected with error:', error); });
3. 實戰(zhàn)
通過實戰(zhàn)理解更加透徹
const handleAdd = () => { if (props.formType === 'detail') return // 禁用“添加危險品”按鈕 const row = { id: undefined, shipName: undefined, voyage: undefined, billNumber: undefined, boxNumber: undefined, boxSize: undefined, boxType: undefined, productName: undefined, hazardousLevel: undefined, hazardCode: undefined, isOpentopOrHigh: undefined, appointmentId: undefined, } row.appointmentId = props.appointmentId const data = AppointmentCommissionApi.getEnterSiteListByAppointmentId(props.appointmentId) console.log(data) // 確保 data 是數(shù)組并賦值給 formData.value.list const fetchedData = Array.isArray(data) ? data : []; formData.value.list = [...formData.value.list, ...fetchedData]; formData.value.list.push(row) // 添加新條目到列表中 console.log('Updated list:', formData.value.list); }
其中data輸出問題所示的內(nèi)容,那么處理此類問題有如下兩種方式
- 使用Promise的
.then()
方法來處理異步API調(diào)用的結(jié)果
const handleAdd = () => { if (props.formType === 'detail') return // 禁用按鈕 const row = { id: undefined, shipName: undefined, voyage: undefined, billNumber: undefined, boxNumber: undefined, boxSize: undefined, boxType: undefined, productName: undefined, hazardousLevel: undefined, hazardCode: undefined, isOpentopOrHigh: undefined, appointmentId: undefined, } row.appointmentId = props.appointmentId // 調(diào)用API并處理結(jié)果 AppointmentCommissionApi.getEnterSiteListByAppointmentId(props.appointmentId) .then(data => { // 確保 data 是數(shù)組并賦值給 formData.value.list const fetchedData = Array.isArray(data) ? data : []; formData.value.list = [...formData.value.list, ...fetchedData]; formData.value.list.push(row); // 添加新條目到列表中 console.log('Updated list:', formData.value.list); }) .catch(error => { console.error('Error fetching data:', error); }); }
- 另一種更現(xiàn)代和清晰的方法是使用
async/await
const handleAdd = async () => { if (props.formType === 'detail') return // 禁用按鈕 const row = { id: undefined, shipName: undefined, voyage: undefined, billNumber: undefined, boxNumber: undefined, boxSize: undefined, boxType: undefined, productName: undefined, hazardousLevel: undefined, hazardCode: undefined, isOpentopOrHigh: undefined, appointmentId: undefined, } row.appointmentId = props.appointmentId try { // 調(diào)用API并等待結(jié)果 const data = await AppointmentCommissionApi.getEnterSiteListByAppointmentId(props.appointmentId); // 確保 data 是數(shù)組并賦值給 formData.value.list const fetchedData = Array.isArray(data) ? data : []; formData.value.list = [...formData.value.list, ...fetchedData]; formData.value.list.push(row); // 添加新條目到列表中 console.log('Updated list:', formData.value.list); } catch (error) { console.error('Error fetching data:', error); } }
以上就是在Vue3中處理異步API調(diào)用并更新表單數(shù)據(jù)的方法示例的詳細(xì)內(nèi)容,更多關(guān)于Vue3處理異步API并更新數(shù)據(jù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
VUE在for循環(huán)里面根據(jù)內(nèi)容值動態(tài)的加入class值的方法
這篇文章主要介紹了VUE在for循環(huán)里面根據(jù)內(nèi)容值動態(tài)的加入class值的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08Vue2.0中三種常用傳值方式(父傳子、子傳父、非父子組件傳值)
在Vue的框架開發(fā)的項目過程中,經(jīng)常會用到組件來管理不同的功能,有一些公共的組件會被提取出來。下面通過本文給大家介紹Vue開發(fā)中常用的三種傳值方式父傳子、子傳父、非父子組件傳值,需要的朋友參考下吧2018-08-08vue如何解決el-select下拉框顯示ID不顯示label問題
這篇文章主要介紹了vue如何解決el-select下拉框顯示ID不顯示label問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06Vue?ELement?Table技巧表格業(yè)務(wù)需求實戰(zhàn)示例
這篇文章主要介紹了Vue?ELement?Table技巧表格業(yè)務(wù)需求實戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11vue實現(xiàn)將數(shù)據(jù)存入vuex中以及從vuex中取出數(shù)據(jù)
今天小編就為大家分享一篇vue實現(xiàn)將數(shù)據(jù)存入vuex中以及從vuex中取出數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11