Vue.js 初步入门
Vue.js Ajax(axios)
Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。
所以必须先引入axios.js
文件。
但凡知道一点JQuery基础的,都会对ajax请求有所了解,下面写一个简单的ajax请求:
$.ajax({
url:"demo_test.txt",
type:'GET',
data:{k1:v1,k2:v2},
success:function(result){
$("#div1").html(result);
}});
请求里包含url路径,请求类型,数据以及成功的回调函数等,axios中的ajax请求也有类似的使用方式。
使用详解
get请求
//通过给定的url发送请求
axios.get('url')
.then(function(response){//成功响应后的回调函数
console.log(response);
})
.catch(function(err){//响应失败后的回调函数
console.log(err);
});
//以上请求也可以通过这种方式来发送
axios.get('url',{
params:{
xx:xxxxx//形式如同name?=zs
}
})
.then(function(response){
console.log(response);
})
.catch(function(err){
console.log(err);
});
post请求
axios.post('url',{
xxx:'xxxxxx',//post请求传递的参数
xxxxx:'xxxxxxx'
})
.then(function(res){
console.log(res);//成功响应后的回调函数
})
.catch(function(err){
console.log(err);//响应失败后的回调函数
});
为方便起见,为所有支持的请求方法提供了别名:
- 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]])
执行多个并发请求
function func1() {
return axios.get('url1');
}
function func2() {
return axios.get('url2');
}
axios.all([func1(), func2()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));