欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在Vue3中處理異步API調(diào)用并更新表單數(shù)據(jù)的方法示例

 更新時間:2024年06月20日 09:41:47   作者:碼農(nóng)研究僧  
這篇文章主要介紹了如何在Vue3中處理異步API調(diào)用并更新表單數(shù)據(jù)(附Demo),文中通過代碼示例講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下

前言

從實戰(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)文章

最新評論