1.axios
1.1使用方法
get请求:
axios.get(url,[options]).then(function(response){
//成功的处理
},function(err){
//失败的处理
}
get如果需要传递options参数,那么写法为{ params: { 参数名称:参数值 } }
delete请求:
axios.delete(url+'/'+options).then(function(response){
//成功的处理
},function(err){
//失败的处理
}
post请求:
axios.post(url,[body]).then(function(response){
//成功的处理
},function(err){
//失败的处理
}
post传递参数和ajax的post相同。
axios与vue结合的简单实例如下:
View Code
上例的两个接口是测试的地址接口。
1.2.注意事项:
a.必须先导入才能使用,网络地址 https://unpkg.com//axios/dist/axios.min.js(学习文档地址:https://github.com/axios/axios);
b.then方法中的回调函数会在请求成功或失败时出发;
c.可以在回调函数中获取响应数据或失败信息;
d.请求的前后this发生了变化,所以需要先把值存储下来,如上例的that。
2.vue-resource
get请求语法
//get请求
this.$http.get(url,[options]).then(res => {
var data=res.body
console.log(data)
},err => {
console.log(err)
})
post请求语法
//get请求
this.$http.post(url,[body],[options]).then(res => {
var data=res.body
console.log(data)
},err => {
console.log(err)
})
手动发起的没有表单格式application/x-www-form-urlencoded,可以设置可选参数为{emulateJSON:true}来改变格式。
delete请求语法
//get请求
this.$http.delete(url,[options]).then(res => {
var data=res.body
console.log(data)
},err => {
console.log(err)
})
jsonp请求语法
//get请求
this.$http.jsonp(url,[options]).then(res => {
var data=res.body
console.log(data)
},err => {
console.log(err)
})
get和sonp的请求格式很类似,如果这三个需要传递options参数,那么写法为{ params: { 参数名称:参数值 } }。对于delete,直接使用restful风格方式,可参考上面axios的delete请求。另外,请求到的数据都在red.body中。
实例1:使用三种方式进行测试,包含删除
View Code
实例2:对于有共同根目录的url,我们可以进行统一的配置,配置及使用如下:
View Code