preface

Vue-resource is a plug-in for vue.js that can initiate a request and process the response via XMLHttpRequest or JSONP. In other words, vue-Resource plug-ins can do what $. Ajax can do, and vue-Resource apis are much cleaner.

Vue-resource is a very lightweight plug-in for handling HTTP requests that provides two ways to handle HTTP requests:

  1. Use vue. HTTP or this.$HTTP

  2. Use vue. resource or this.$resource

The two approaches are essentially the same, and reading the vue-Resource source code, you can see that the second approach is based on the first approach.

In addition, Vue-Resource provides interceptors: Inteceptor can append behavior before and after a request, which means that we can control all aspects of the request except the processing of the request.

In vue.js, there are two ways to complete ajax requests: Vue-Resource and Axios.

Vue. Js version 2.0 recommends using AXIOS to complete Ajax requests.

vue-resourceThe characteristics of

  • Small size: Vue-Resource is very small, only about 12KB when compressed, and 4.5KB when gzip is enabled on the server, which is much smaller than jQuery.

  • Support for mainstream browsers: Like vue. js, vue-resource is supported by all major browsers except IE9.

  • Support for Promise apis and URI Templates: Promise is an ES6 feature. Promise means “prophet” in Chinese, and Promise objects are used for asynchronous computation. URI Templates represent URI Templates, somewhat like the ASP.NET MVC routing Templates;

  • Support for interceptors: Interceptors are global and can do some processing before and after a request is sent. Interceptors can be useful in situations such as setting access_token in HEADERS before a request is sent, or providing a common handling if a request fails.

The basic grammar

With the introduction of vue-Resource, HTTP can be used either on a global VUE object or on a vUE instance.

  • Use HTTP based on global Vue objects
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
Copy the code
  • Used within a Vue instance$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
Copy the code

Here is a simple get usage example:

// GET /someUrl
  this.$http.get('/someUrl').then(response => {
    // success callback
  }, response => {
    // error callback
  });
Copy the code

HTTP method List

Vue-resource’s request API is designed in the REST style and provides seven request apis:

  • get(url, [options])
  • head(url, [options])
  • delete(url, [options])
  • jsonp(url, [options])
  • post(url, [body], [options])
  • put(url, [body], [options])
  • patch(url, [body], [options])

In addition to JSONP, the other six API names are standard HTTP methods. When the server uses REST apis, the client-side and server-side coding styles are nearly identical, which reduces communication costs for front-end and back-end developers.

  • optionsobject

The options object when sending the request contains the following properties:

  • Response

Returns the following parameters and methods for the object:

The sample code

Simple POST submission

{
  // 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
  });
}
Copy the code

GET requests with query parameters and custom request headers

{
// GET /someUrl? foo=bar
this.$http.get('/someUrl', {params: {foo: 'bar'}, headers: {'X-Custom': '... '}}).then(response => {
  // success callback
}, response => {
  // error callback
});
}
Copy the code

Get the picture and extract the body content of the picture from the response using the blob() method.

// GET /image.jpg
this.$http.get('/image.jpg', {responseType: 'blob'}).then(response => {
  // resolve to Blob
  return response.blob();
}).then(blob => {
  // use image Blob
});
Copy the code

The installation

npm install vue-resource --save
Copy the code

– The save parameter adds the corresponding configuration to our package.json configuration file. After the installation is successful, you can look at the package.json file and you will see the configuration of “vUE -resource”: “^1.3.4”. Details are as follows:

"dependencies": {
    "vue": "^ 2.3.3." "."vue-resource": "^" 1.3.4."vue-router": "^ 2.7.0"
  },
Copy the code

application

Through the above steps, we have vue-Resource installed, but how do we use it in vue-CLI?

First, we need to import and register vue-resource in the main.js file:

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

Resource Service Application

Vue-resource provides another way to access the HTTP — Resource service, which contains the following default actions:

  • get: {method: 'GET'},
  • save: {method: 'POST'},
  • query: {method: 'GET'},
  • update: {method: 'PUT'},
  • remove: {method: 'DELETE'},
  • delete: {method: 'DELETE'}

Resource objects can also be accessed in two ways: global and local.

// Global access

Vue.resource
Copy the code

// Local access

this.$resource
Copy the code

This can be used in conjunction with URI Template, and the apiUrl is set to {/id} in the following examples:

apiUrl: 'HTTP: / / http://22.189.25.95:8080/api/customers / {id}'
Copy the code

{/id} is a placeholder that is replaced when the actual argument is passed. For example, {id: vm. Item. CustomerId} in the vm. The item. The customerId is 12, then send the request URL is: ‘http://22.189.25.95:8080/api/customers/12’

2. Example

// Use the get method to send a get request without specifying {/id}
getCustomers: function() {
    var resource = this.$resource(this.apiUrl),
        vm = this;
    resource.get().then((response) => {
        vm.$set('gridData', response.data); }).catch(function(response) { console.log(response); })}// Use the save method to send a POST request without specifying {/id}
createCustomer: function() {
    var resource = this.$resource(this.apiUrl),
        vm = this;
    resource.save(vm.apiUrl, vm.item).then((response) => {
        vm.$set('item'{}); vm.getCustomers(); }); this.show =false;
}


// Use the update method to send a PUT request, which specifies {/id}.
updateCustomer: function() {
    varresource = this.$resource(this.apiUrl), vm = this; resource.update({ id: vm.item.customerId }, vm.item).then((response) => { vm.getCustomers(); })}Copy the code