前言 vue-resource
vue-resource是Vue.js的插件提供了使用XMLHttpRequest或JSONP進(jìn)行Web請(qǐng)求和處理響應(yīng)的服務(wù)互拾。 當(dāng)vue更新到2.0之后,作者就宣告不再對(duì)vue-resource更新,而是推薦的axios灯荧,在這里大家了解一下vue-resource就可以。vue-resource的github: https://github.com/pagekit/vue-resource
1 axios
Axios 是一個(gè)基于 promise 的 HTTP 庫(kù)窝撵,可以用在瀏覽器和 node.js 中
axios的github:https://github.com/axios/axios
我們以restful風(fēng)格開(kāi)發(fā)為例,說(shuō)明Vue中ajax的使用方式
1. get請(qǐng)求
//通過(guò)給定的ID來(lái)發(fā)送get請(qǐng)求
axios.get('/user?ID=12345')
.then(function(response){
console.log(response);
})
.catch(function(err){
console.log(err);
});
//以上請(qǐng)求也可以通過(guò)這種方式來(lái)發(fā)送
axios.get('/user',{
params:{
ID:12345
}
})
.then(function(response){
console.log(response);
})
.catch(function(err){
console.log(err);
});
2.post請(qǐng)求,帶參數(shù)
axios.post('/user',{
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err);
});
為方便起見(jiàn)俺夕,為所有支持的請(qǐng)求方法提供了別名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])