1. 程式人生 > >Vue基礎篇-Ajax請求(axios)

Vue基礎篇-Ajax請求(axios)

1.基礎知識

(a)vue2.0官方推薦使用axios,vue-resource是vue1.0時代的產物(已然下崗待業);

(b)Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中;

(c)axios基本功能包括:攔截請求和響應,轉換請求資料,併發請求,取消請求,自轉換JSON資料等;

(d)axios.js指令碼檔案需自行下載

2.基本語法

//get請求
axios.get('../data/getData',{
    params:{
        canshu001:2,
        canshu002:2
    }
}).then(function(response){
    self.dataReturn=response.data;
}).catch(function(error){
    console.log(error);
});

//post請求(注意的是傳遞引數的書寫方法不同,沒有params接受)
axios.post('../data/getData',{
    canshu001:2,
    canshu002:2
}).then(function(response){
    self.dataReturn=response.data;
}).catch(function(error){
    console.log(error);
});

3.併發請求

function getUser1() {
  return axios.get('/user/12345');
}
function getUser2() {
  return axios.get('/user/12345/other');
}

axios.all([getUser1(), getUser2()])
  .then(axios.spread(function (reg1, reg2) {
    // 兩個請求執行完成,reg1為getUser1返回的結果,reg2為getUser2返回的結果
}));

4.axios的相關API

1)axios(config)   config就是配置項物件

// 傳送 POST 請求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

(2)axios(url[, config])    請求別名,各請求的簡寫模式

axios.request({data:{"name":"yin"}}).then();
axios.get("user/12345",{params:{"name":"yin"}}).then();
axios.delete("user/12345",{params:{"name":"yin"}}).then();
axios.head("user/12345",{params:{"name":"yin"}}).then();
axios.post("user/12345",{"name":"yin"}).then();
axios.put("user/12345",{"name":"yin"}).then();
axios.patch("user/12345",{"name":"yin"}).then();

(3)併發請求    axios.all([ ])傳送請求    axios.spread(callback)接受結果(詳情看3)

(4)請求配置config(常用)

url 請求地址 -
method 請求方式 預設:get
data 請求引數物件  
timeout 超時毫秒數 超出時間,請求將會中斷
proxy 代理伺服器的主機名和埠 提供允許訪問的許可權
cancelToken 指定用於取消請求的  

(5)響應結果

data:{} 返回結果
status:200 狀態碼
statusText:'OK' 狀態資訊
headers:{} 響應頭
config:{} 請求時的配置項集合