在Vue3中處理異步API調(diào)用并更新表單數(shù)據(jù)的方法示例
前言
從實(shí)戰(zhàn)問(wèn)題中剖析知識(shí)點(diǎn)
1. 問(wèn)題所示
執(zhí)行Vue3數(shù)據(jù)的時(shí)候,終端輸出的data如下所示
Promise {<pending>}
[[Prototype]] : Promise
[[PromiseState]] : "fulfilled"
[[PromiseResult]] : Array(13)
截圖如下所示:

2. 知識(shí)分析
輸出的數(shù)據(jù)是JavaScript的Promise對(duì)象的
對(duì)于這個(gè)數(shù)據(jù)基本的數(shù)據(jù)分析如下:
Promise {<pending>}:Promise對(duì)象的初始狀態(tài),處于等待狀態(tài)[[Prototype]]: Promise:對(duì)象的原型鏈,通過(guò)Promise構(gòu)造函數(shù)創(chuàng)建的[[PromiseState]]: "fulfilled":Promise對(duì)象的內(nèi)部狀態(tài),已經(jīng)成功完成[[PromiseResult]]: Array(13):對(duì)象的結(jié)果
對(duì)于Promise的狀態(tài)有如下:
- Pending(待定):Promise剛創(chuàng)建時(shí)的初始狀態(tài)
- Fulfilled(成功):操作成功完成,Promise有了結(jié)果
- Rejected(失?。?/strong>:操作失敗,Promise有了失敗的原因
Promise的結(jié)果:當(dāng)Promise狀態(tài)變?yōu)閒ulfilled時(shí),會(huì)有一個(gè)對(duì)應(yīng)的結(jié)果值,這里是一個(gè)包含13個(gè)元素的數(shù)組
正確處理Promise的結(jié)果,例如使用.then()和.catch()方法
比如查看輸出內(nèi)容:
myPromise.then(result => console.log(result));
做適當(dāng)?shù)腻e(cuò)誤處理:
myPromise
.then(result => {
console.log(result);
})
.catch(error => {
console.error('Error:', error);
});
給個(gè)示例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. 實(shí)戰(zhàn)
通過(guò)實(shí)戰(zhàn)理解更加透徹
const handleAdd = () => {
if (props.formType === 'detail') return // 禁用“添加危險(xiǎn)品”按鈕
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輸出問(wèn)題所示的內(nèi)容,那么處理此類問(wèn)題有如下兩種方式
- 使用Promise的
.then()方法來(lái)處理異步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ù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
VUE在for循環(huán)里面根據(jù)內(nèi)容值動(dòng)態(tài)的加入class值的方法
這篇文章主要介紹了VUE在for循環(huán)里面根據(jù)內(nèi)容值動(dòng)態(tài)的加入class值的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-08-08
vue+webpack實(shí)現(xiàn)異步組件加載的方法
下面小編就為大家分享一篇vue+webpack實(shí)現(xiàn)異步組件加載的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-02-02
Vue2.0中三種常用傳值方式(父?jìng)髯印⒆觽鞲浮⒎歉缸咏M件傳值)
在Vue的框架開(kāi)發(fā)的項(xiàng)目過(guò)程中,經(jīng)常會(huì)用到組件來(lái)管理不同的功能,有一些公共的組件會(huì)被提取出來(lái)。下面通過(guò)本文給大家介紹Vue開(kāi)發(fā)中常用的三種傳值方式父?jìng)髯?、子傳父、非父子組件傳值,需要的朋友參考下吧2018-08-08
關(guān)于vue.extend的使用及說(shuō)明
這篇文章主要介紹了關(guān)于vue.extend的使用及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
vue如何解決el-select下拉框顯示ID不顯示label問(wèn)題
這篇文章主要介紹了vue如何解決el-select下拉框顯示ID不顯示label問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Vue?ELement?Table技巧表格業(yè)務(wù)需求實(shí)戰(zhàn)示例
這篇文章主要介紹了Vue?ELement?Table技巧表格業(yè)務(wù)需求實(shí)戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
vue實(shí)現(xiàn)將數(shù)據(jù)存入vuex中以及從vuex中取出數(shù)據(jù)
今天小編就為大家分享一篇vue實(shí)現(xiàn)將數(shù)據(jù)存入vuex中以及從vuex中取出數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11

