[Vue]: vue-resource achieve get, post, jsonp request

vue-resource achieve get, post, jsonp request

Common data type of request: get, post, jsonp

In addition vue-resource, you can also use axiosa third party package to fulfill the request for data

vue-resourceOfficial Documents

vue-resource configuration steps:

  • Directly in the page, by scriptthe label, the introduction of vue-resourcethe script file;
<script src="./lib/vue-2.4.0.js"></script>
<script src="./lib/vue-resource-1.3.4.js"></script>
  • Note: the order is quoted: quote from Vuethe script file, and then referenced vue-resourcescript file;
  1. Send a get request:
    • When initiating get request, by .thensetting a successful callback function
getInfo() { // get 方式获取数据
  this.$http.get('http://127.0.0.1:8899/api/getlunbo').then(res => {
    console.log(res.body);
  })
}
  1. Send a post request:
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 request the data transmission:
jsonpInfo() { // JSONP形式从服务器获取数据
  var url = 'http://127.0.0.1:8899/api/jsonp';
  this.$http.jsonp(url).then(res => {
    console.log(res.body);
  });
}

By global configuration , settings and other parameters BaseURL, for example:

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

Note: If we pass the global configuration, data interface root domain name request, the http request initiated each time alone, url path of the request, it should start with a relative path in front can not take /, or do not enable the root path splicing .

Guess you like

Origin www.cnblogs.com/moon1992/p/11075013.html