使用vue-resource

使用vue-resource

注意事项:

  1. 下载并导入vue-resource(将挂载一个this.$http这个属性)
  2. 它依赖于vue,要先导入vue再导入vue-resource
// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
Vue.http.jsonp(url, [options]).then(successCallback, errorCallback);
// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
this.$http.jsonp(url, [options]).then(successCallback, errorCallback);

:post[ ]不能省,body,就是要传入后端的数据,options为配置对象,都由一个{}包裹的参数对象,successCallback为成功的回调,必需要;errorCallback为失败回调,随意;
.then都是由promise封装的,

进行发起get请求:
methods:{
getBookList() {
this.$http.get(“http://127.0.0.1/admin/product_list.php”).then(result => {
if (result.status === 200) {
// console.log(result.body); 使用时先打印到后台查看输出的数据信息,查看需要的数据
this.list = result.body; //将body里的数据给list再进行遍历渲染
}
});
},
}

发起post请求
post:function(){
//发送 post 请求
this.$http.post(’/try/ajax/demo_test_post.php’,{name:“菜鸟教程”,url:“http://www.runoob.com”},{emulateJSON:true}).then(function(res){
console.log(res.body);
});
出现这个报错:在这里插入图片描述
原因:手动发起的post请求,默认没有表单格式,有的服务器处理不了
就必须在第三个参数里加入{emulateJSON:true},设置提交类型为普通表单数据格式

发起jsonp请求:
post:function(){
//发送 post 请求
this.$http.jsonp(’/try/ajax/demo_test_post.php’).then(function(res){
console.log(res.body);
});

发布了11 篇原创文章 · 获赞 2 · 访问量 751

猜你喜欢

转载自blog.csdn.net/qq_41589917/article/details/101283561