Vue.js数据请求方式

Vue.js数据请求方式

一、 vue-resource

1>通过 yarn 或者 NPM.安装

$ yarn add vue-resource
$ npm install vue-resource

2>在main.js中引用并使用它

import VueResource from 'vue-resource'
Vue.use(VueResource)

3>vue-resource中常用的请求方式(jsonp请求解决跨域问题)

this.$http.get('/someUrl', [config]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [config]).then(successCallback, errorCallback);
this.$http.jsonp('/someUrl', [config]).then(successCallback, errorCallback);

4>案例
(1)带有参数的post请求

{
  // POST /someUrl
  this.$http.post('/someUrl', {foo: 'bar'}).then(response => {

    // get status
    response.status;

    // get status text
    response.statusText;

    // get 'Expires' header
    response.headers.get('Expires');

    // get body data
    this.someData = response.body;

  }, response => {
    // error callback
  });
}

(2)发送带有URL查询参数和自定义头的GET请求。

 this.$http.get('/someUrl', {params: {foo: 'bar'}}).then(response => {
    // success callback
  }, response => {
    // error callback
  });

更多相关需求请看官网文档:
https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

二、axios

1>使用npm安装

$ npm install axios

2>使用案例
(1)带参数的get请求

const axios = require('axios');       //一定要引入哦
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

(2)带参数的post请求

const axios = require('axios');
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

以上两种方式还可以通过将相关配置传递给axios来发出请求。例如

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

更多相关需求请看官网文档:https://github.com/axios/axios

猜你喜欢

转载自blog.csdn.net/weixin_38483133/article/details/86489105