在vue中,咱們不可能爲了網絡請求而特地引入jQuery,以前vue裏有vue-resource來解決網絡請求問題,後來官方建議使用axios,而vue-resource則再也不維護。vue
axios的詳細教程見github地址:
https://github.com/axios/axiosios
安裝:
npm install axios
或
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>git
使用:github
1、配置文件式:npm
axios(config).then(res=>{to-do}).catch(err=>{to-do})
以get和post請求說明axios
//get: axios({ method:'GET', url:'http://www.zhouxiaohouer.com/api/getsth', params:{ name:'黃燜雞米飯', price:34 } }).then(res=>{ console.log(res.data) }).catch(err=>{ console.log(err) }) //post: axios({ method:'POST', url:'http://www.zhouxiaohouer.com/api/poststh', data:{ name:'黃燜雞米飯', price:34 }, headers: { 'Content-Type':'application/x-www-form-urlencoded' }, transformRequest: [function (data, headers) { //轉換data數據的數據格式,通常返回一個序列化的字符串 //axios內封裝了一個qs模塊,引入後能夠直接轉換 return data; }], }).then(res=>{ console.log(res.data) }).catch(err=>{ console.log(err) })
2、別名式:api
axios.get(url[, config])
axios.post(url[, data[, config]])
以一個在vue組件裏的部分代碼說明網絡
import axios from 'axios' import qs from 'qs' getGoods(){ var _this = this var data = { filter:'-_id -__v', } axios.post( 'http://www.zhouxiaohouer.com/api/poststh', qs.stringify(data), { headers: { 'Content-Type':'application/x-www-form-urlencoded' } }) .then( res=>{ _this.msg = JSON.stringify(res.data) }, err =>{ console.log(err) } ) }
在axios中,咱們還能夠事先配置默認的全局配置app
axios.defaults.baseURL = 'https://www.zhouxiaohouer.com/api'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'