[Vue] : vue-resource 实现 get, post, jsonp请求

vue-resource 实现 get, post, jsonp请求

常见的数据请求类型:get,post,jsonp

除了vue-resource之外,还可以使用axios的第三方包实现实现数据的请求

vue-resource官方文档

vue-resource 的配置步骤:

  • 直接在页面中,通过script标签,引入 vue-resource 的脚本文件;
<script src="./lib/vue-2.4.0.js"></script>
<script src="./lib/vue-resource-1.3.4.js"></script>
  • 注意:引用的先后顺序是:先引用 Vue 的脚本文件,再引用 vue-resource 的脚本文件;
  1. 发送get请求:
    • 当发起get请求之后, 通过.then来设置成功的回调函数
getInfo() { // get 方式获取数据
  this.$http.get('http://127.0.0.1:8899/api/getlunbo').then(res => {
    console.log(res.body);
  })
}
  1. 发送post请求:
postInfo() {
  var url = 'http://127.0.0.1:8899/api/post';
  // post 方法接收三个参数:
  // 参数1: 要请求的URL地址
  // 参数2: 要发送的数据对象
  // 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded
  this.$http.post(url, { name: 'zs' }, { emulateJSON: true }).then(res => {
    console.log(res.body);
  });
}
  1. 发送JSONP请求获取数据:
jsonpInfo() { // JSONP形式从服务器获取数据
  var url = 'http://127.0.0.1:8899/api/jsonp';
  this.$http.jsonp(url).then(res => {
    console.log(res.body);
  });
}

可以通过全局配置,设置BaseURL等参数,例如:

Vue.http.options.root = 'http://vue.studyit.io/'
// 全局启用 emulateJSON 选项
Vue.http.options.emulateJSON = true

注意:如果我们通过全局配置了,请求的数据接口根域名,则在每次单独发起 http 请求的时候,请求的 url 路径,应该以相对路径开头,前面不能带/,否则不会启用根路径做拼接。

猜你喜欢

转载自www.cnblogs.com/moon1992/p/11075013.html