20181205——Vue中的axios
阿新 • • 發佈:2018-12-09
axios安裝
npm install axios
基本使用方法
get請求
getCityInfo () {
axios.get('/api/city.json')
.then(this.handleGetCityInfoSucc)
},
//來自我的travel中的程式碼
// Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
POST請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
同時執行多個請求
function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete }));
axios API
Response
當我們ajax獲取資料成功後會返回一個response物件,它包含了以下內容:
{ // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with headers: {}, // `config` is the config that was provided to `axios` for the request config: {} }
為何放棄vue-resource
最近團隊討論了一下,Ajax 本身跟 Vue 並沒有什麼需要特別整合的地方,使用 fetch polyfill 或是 axios、superagent 等等都可以起到同等的效果,vue-resource 提供的價值和其維護成本相比並不划算,所以決定在不久以後取消對 vue-resource 的官方推薦。已有的使用者可以繼續使用,但以後不再把 vue-resource 作為官方的 ajax 方案。