尤雨溪之前在微博發佈消息,不再繼續維護vue-resource,並推薦大家開始使用 axios 。
一、axios 簡介
axios 是一個基於Promise 用於瀏覽器和 nodejs 的 HTTP 客戶端,它本身具有以下特徵:https://hzzly.github.io/2017/03/12/axios%E5%9C%A8vue%E4%B8%AD%E7%9A%84%E7%AE%80%E5%8D%95%E9%85%8D%E7%BD%AE%E4%B8%8E%E4%BD%BF%E7%94%A8/
- 從瀏覽器中創建 XMLHttpRequest
- 從 node.js 發出 http 請求
- 支持 Promise API
- 攔截請求和響應
- 轉換請求和響應數據
- 取消請求
- 自動轉換JSON數據
- 客戶端支持防止 CSRF/XSRF
二、引入方式:
npm:
1 2 3
|
$ npm install axios //淘寶源 $ cnpm install axios
|
bower:
1
|
$ bower install axios
|
cdn:
1
|
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
|
三、vue中axios的配置
之前那個開源項目一開始就打算用axios,在網上找了好多文章與攻略,發現好多都不太詳細,所以打算自己動手配置一個,(不要慫,擼起袖子就是幹)。
我的配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
import axios from 'axios' import qs from 'qs' import * as _ from '../util/tool' axios.defaults.timeout = 5000; //響應時間 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; //配置請求頭 axios.defaults.baseURL = '你的接口地址'; //配置接口地址 //POST傳參序列化(添加請求攔截器) axios.interceptors.request.use((config) => { //在發送請求之前做某件事 if(config.method === 'post'){ config.data = qs.stringify(config.data); } return config; },(error) =>{ _.toast("錯誤的傳參", 'fail'); return Promise.reject(error); }); //返回狀態判斷(添加響應攔截器) axios.interceptors.response.use((res) =>{ //對響應數據做些事 if(!res.data.success){ // _.toast(res.data.msg); return Promise.reject(res); } return res; }, (error) => { _.toast("網絡異常", 'fail'); return Promise.reject(error); }); //返回一個Promise(發送post請求) export function fetch(url, params) { return new Promise((resolve, reject) => { axios.post(url, params) .then(response => { resolve(response.data); }, err => { reject(err); }) .catch((error) => { reject(error) }) }) }
|
四、vue中使用配置好的axios
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
export default { /** * 用戶登錄 */ Login(params) { return fetch('/users/api/userLogin', params) }, /** * 用戶註冊 */ Regist(params) { return fetch('/users/api/userRegist', params) }, /** * 發送註冊驗證碼 */ RegistVerifiCode(tellphone) { return fetch('/users/api/registVerifiCode', {tellphone: tellphone}) }, ...... }
|
如果覺得還行,歡迎star
項目地址: https://github.com/hzzly/xyy-vue
demo地址: http://hjingren.cn/xyy-vue/
好了,溜了溜了。。。