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

vue .then和鏈?zhǔn)秸{(diào)用操作方法

 更新時(shí)間:2023年07月13日 10:05:05   作者:tenc1239  
這篇文章主要介紹了vue .then和鏈?zhǔn)秸{(diào)用操作方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

Vue.then

一、Vue.then是什么意思

Vue.then是Vue.js框架中對(duì)于異步操作進(jìn)行處理的一個(gè)方法。它與Promise結(jié)合使用,相當(dāng)于Promise中的then方法,可以處理異步操作的結(jié)果,從而實(shí)現(xiàn)對(duì)后續(xù)流程的控制和處理。Vue.then方法是在Vue.js 2.1版本中引入的,目的是更好地支持異步操作。

二、Vue.then的使用

使用Vue.then方法,需要先進(jìn)行異步操作,接著通過(guò)調(diào)用Promise中的then方法來(lái)對(duì)異步操作的結(jié)果進(jìn)行處理。例如,在Vue.js中,可以使用Vue resource庫(kù)實(shí)現(xiàn)請(qǐng)求后臺(tái)數(shù)據(jù)的異步操作,代碼如下:

Vue.http.get('/api/user')
    .then(response => {
        this.users = response.body;
    }, response => {
        console.log('error');
    });

上述代碼中,先進(jìn)行了一個(gè)異步操作,即調(diào)用Vue.http.get方法來(lái)請(qǐng)求后臺(tái)數(shù)據(jù)。然后,將結(jié)果通過(guò)Promise的then方法進(jìn)行處理,從而實(shí)現(xiàn)對(duì)于數(shù)據(jù)結(jié)果的控制。在這個(gè)例子中,如果響應(yīng)成功,返回?cái)?shù)據(jù)的主體內(nèi)容(response.body)將被賦值給該Vue實(shí)例的users變量,否則會(huì)在控制臺(tái)輸出"error"。

vue .then和鏈?zhǔn)秸{(diào)用

1 如果下級(jí)函數(shù)存在異步操作,

并且上級(jí)函數(shù)需要等待下級(jí)函數(shù)的異步操作完成后再繼續(xù)執(zhí)行,

那么在上級(jí)函數(shù)中就需要使用 .then() 方法來(lái)處理異步操作的結(jié)果。

2在let obj =  axios.get(path).then((resp => { return resp })

這個(gè)鏈?zhǔn)秸{(diào)用中,確實(shí)會(huì)有兩個(gè)返回值。

第一個(gè)值是 請(qǐng)求的結(jié)果axios.get(path)

第二個(gè)值是.then()中數(shù)據(jù)處理后的結(jié)果 Promise 對(duì)象 obj 。

.then返回值是Promise 對(duì)象

4發(fā)起異步請(qǐng)求:axios.get(path) 得到第一返回值處理響應(yīng)結(jié)果:.then((resp) => { ... }) 得到第二返回值Promise 對(duì)象上級(jí)函數(shù)調(diào)用下級(jí)帶.then的函數(shù)必須 .then((data) => { ... })

5 上級(jí)函數(shù) 使用了.then(), 下級(jí)函數(shù)可以不使用.then,直接返回請(qǐng)求結(jié)果

第一種 上級(jí)函數(shù) .then() ,下級(jí)函數(shù).then() 返回處理完的數(shù)據(jù)

export function funcB() {
  let newData = []
    newData = fetchData().then((data) => {
      console.log(data); // 直接使用數(shù)據(jù)
      return data;
    });
    console.log(newData);
  }
  return newData;
}
function fetchData() {
  try {
    let path = 'dt.csv'
    let obj = axios.get(path).then((resp) => {
        // 這里處理數(shù)據(jù)
         return data;
        })
    return obj; // 返回Promise 對(duì)象
  } catch (error) {
    // 處理錯(cuò)誤
    console.error(error);
    return null;
  }
}

第二種 上級(jí)函數(shù) .then() ,下級(jí)函數(shù)只返回請(qǐng)求結(jié)果

export function funcB() {
  let newData = []
    newData = fetchData().then((data) => {
    // 這里處理數(shù)據(jù)
      console.log(data); // 在這里處理 newData
      return data;
    });
    console.log(newData);
  }
  return newData;
}
function fetchData() {
  try {
    let path = 'dt.csv'
    let obj = axios.get(path)
    return obj; // 返回Promise 對(duì)象
  } catch (error) {
    // 處理錯(cuò)誤
    console.error(error);
    return null;
  }
}

到此這篇關(guān)于vue .then和鏈?zhǔn)秸{(diào)用的文章就介紹到這了,更多相關(guān)vue鏈?zhǔn)秸{(diào)用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論