Overview
In the previous article, we introduced how to use $.ajax and combine it and implemented a simple cross-domain CURD example. It is data-driven, which makes us not need to operate the DOM directly. If we do not need to use the DOM selector of jQuery, there is no need to introduce jQuery. vue-resource is a plugin that can initiate requests and process responses via XMLHttpRequest or JSONP. In other words, the vue-resource plug-in can do what $.ajax can do, and the vue-resource API is simpler. In addition, vue-resource also provides a very useful inteceptor function. Using inteceptor can add some behavior before and after the request, such as using inteceptor to display the loading interface when ajax request.
The main content of this article is as follows:
- Introduce the characteristics of vue-resource
- Introduction to the basic usage method of vue-resource
- Example of adding, deleting, searching and modification based on this.$http
- Example of adding, deleting, searching and modification based on this.$resource
- Implement the loading screen when requesting waiting based on inteceptor
- The prompt screen when request error is implemented based on inteceptor
Source code of 11 examples in this article:http://xiazai./201701/yuanma/vue-resource_jb51.rar
Vue-resource features
The vue-resource plug-in has the following features:
1. Small size
vue-resource is very small, only about 12KB after compression, and only 4.5KB after gzip compression is enabled on the server, which is much smaller than jQuery's size.
2. Support mainstream browsers
Like, except for browsers below IE 9, vue-resource supports it.
3. Support Promise API and URI Templates
Promise is a feature of ES6. The Chinese meaning of Promise is "prophet". The Promise object is used for asynchronous calculation.
URI Templates represents URI templates, some similar to MVC routing templates.
4. Support interceptors
The interceptor is global, and the interceptor can do some processing before and after the request is sent.
Interceptors are very useful in some scenarios, such as setting access_token in headers before the request is sent, or providing a common processing method when the request fails.
vue-resource usage
Introduce vue-resource
<script src="js/"></script> <script src="js/"></script>
Basic syntax
After introducing vue-resource, you can use http based on global Vue objects, or http based on a Vue instance.
// Use http based on global Vue objects('/someUrl', [options]).then(successCallback, errorCallback); ('/someUrl', [body], [options]).then(successCallback, errorCallback); // Use $http within a Vue instancethis.$('/someUrl', [options]).then(successCallback, errorCallback); this.$('/someUrl', [body], [options]).then(successCallback, errorCallback);
After sending the request, use the then method to process the response result. Then method has two parameters. The first parameter is the callback function when the response is successful, and the second parameter is the callback function when the response fails.
There are two ways to write callback functions of the then method. The first is the traditional function writing method, and the second is the more concise Lambda writing method of ES 6:
// Traditional writingthis.$('/someUrl', [options]).then(function(response){ // Response successfully callback}, function(response){ // Response to error callback}); // Lambda writing methodthis.$('/someUrl', [options]).then((response) => { // Response successfully callback}, (response) => { // Response to error callback});
PS: People who have done .NET development must have a familiar feeling about the way to write Lambda.
Supported HTTP methods
vue-resource's request API is designed in REST style and provides 7 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 6 API names are standard HTTP methods. When the server uses the REST API, the coding style of the client and the coding style of the server are almost the same, which can reduce the communication costs of front-end and back-end developers.
Client request method | Server-side processing method |
---|---|
this.$(...) | Getxxx |
this.$(...) | Postxxx |
this.$(...) | Putxxx |
this.$(...) | Deletexxx |
options object
The options option object when sending a request contains the following properties:
parameter | type | describe |
---|---|---|
url | string |
The requested URL |
method | string |
The requested HTTP method, such as: 'GET', 'POST' or other HTTP methods |
body |
Object , FormData string
|
request body |
params | Object |
Requested URL parameter object |
headers | Object |
request header |
timeout | number |
Request timeout in milliseconds (0 Indicates no timeout) |
before | function(request) |
The processing function before requesting is sent, similar to jQuery's beforeSend function |
progress | function(event) |
ProgressEventCallback processing function |
credentials | boolean |
Indicates whether credentials are required for cross-domain requests |
emulateHTTP | boolean |
When sending PUT, PATCH, DELETE requests, send them in HTTP POST, and set the request headerX-HTTP-Method-Override
|
emulateJSON | boolean |
Put the request body toapplication/x-www-form-urlencoded content type send |
The role of emulateHTTP
If the web server cannot handle REST style requests such as PUT, PATCH, and DELETE, you can enable enulateHTTP phenomenon. When enabled, the request will be issued in a normal POST method, and the X-HTTP-Method-Override property of the HTTP header information will be set to the actual HTTP method.
= true;
The role of emulateJSON
If the web server cannot handle requests encoded as application/json, you can enable the emulateJSON option. When enabled, the request takes application/x-www-form-urlencoded as the MIME type, just like a normal HTML form.
= true;
Response object
The response object contains the following properties:
method | type | describe |
---|---|---|
text() | string |
Return response body in string form |
json() | Object |
Return response body as JSON object |
blob() | Blob |
Return response body in binary form |
property | type | describe |
ok | boolean |
When the HTTP status code of the response is between 200 and 299, this property is true. |
status | number |
Responsive HTTP status code |
statusText | string |
Responsive status text |
headers | Object |
Response header |
Note: The vue-resource version of this article is v0.9.3. If you are using a version before v0.9.0, the response object does not have json(), blob(), and text() methods.
CURD Example
Tip: The following example still uses the components and WebAPI in the previous article. I will not post the component code and page HTML code of the component.
GET Request
var demo = new Vue({ el: '#app', data: { gridColumns: ['customerId', 'companyName', 'contactName', 'phone'], gridData: [], apiUrl: 'http://211.149.193.19:8080/api/customers' }, ready: function() { () }, methods: { getCustomers: function() { this.$() .then((response) => { this.$set('gridData', ) }) .catch(function(response) { (response) }) } } })
The then method of this program only provides successCallback, and omits errorCallback.
The catch method is used to catch the exception of the program. The catch method and errorCallback are different. The errorCallback is only called when the response fails, while the catch is called during the entire request to the response process.
In the callback function of the then method, you can also use this directly, this still points to the Vue instance:
getCustomers: function() { this.$() .then((response) => { this.$set('gridData', ) }) .catch(function(response) { (response) }) }
To reduce the search of scope chains, it is recommended to use a local variable to receive this.
JSONP request
getCustomers: function() { this.$().then(function(response){ this.$set('gridData', ) }) }
POST request
var demo = new Vue({ el: '#app', data: { show: false, gridColumns: [{ name: 'customerId', isKey: true }, { name: 'companyName' }, { name: 'contactName' }, { name: 'phone' }], gridData: [], apiUrl: 'http://211.149.193.19:8080/api/customers', item: {} }, ready: function() { () }, methods: { closeDialog: function() { = false }, getCustomers: function() { var vm = this vm.$() .then((response) => { vm.$set('gridData', ) }) }, createCustomer: function() { var vm = this vm.$(, ) .then((response) => { vm.$set('item', {}) () }) = false } } })
PUT request
updateCustomer: function() { var vm = this vm.$( + '/' + , ) .then((response) => { () }) }
Delete Request
deleteCustomer: function(customer){ var vm = this vm.$( + '/' + ) .then((response) => { () }) }
Use resource services
vue-resource provides another way to access HTTP-resource service. The resource service contains the following default actions:
get: {method: 'GET'}, save: {method: 'POST'}, query: {method: 'GET'}, update: {method: 'PUT'}, remove: {method: 'DELETE'}, delete: {method: 'DELETE'}
There are also two ways to access the resource object:
- Global access:
- Instance access: this.$resource
Resource can be used in conjunction with URI Template. The apiUrl in the following example is set to {/id}:
apiUrl: 'http://211.149.193.19:8080/api/customers{/id}'
GET Request
Use the get method to send a GET request, and the following request does not specify {/id}.
getCustomers: function() { var resource = this.$resource() vm = this () .then((response) => { vm.$set('gridData', ) }) .catch(function(response) { (response) }) }
POST request
Use the save method to send a POST request, and the following request does not specify {/id}.
createCustomer: function() { var resource = this.$resource() vm = this (, ) .then((response) => { vm.$set('item', {}) () }) = false }
PUT request
Use the update method to send a PUT request, and the following request specifies {/id}.
updateCustomer: function() { var resource = this.$resource() vm = this ({ id: }, ) .then((response) => { () }) }
{/id} is equivalent to a placeholder, which will be replaced when the actual parameter is passed.
For example, if the {id: } is 12, then the request URL sent is:
http://211.149.193.19:8080/api/customers/12
DELETE request
Use the remove or delete method to send a DELETE request. The following request specifies {/id}.
deleteCustomer: function(customer){ var resource = this.$resource() vm = this ({ id: }) .then((response) => { () }) }
Use interceptor
The interceptor can do some processing before and after the request is sent.
Basic usage
((request, next) => { // ... // Processing logic before request sending // ... next((response) => { // ... // Processing logic after request sending // ... // Depending on the request status, the response parameter will be returned to successCallback or errorCallback return response }) })
Before the response is returned to successCallback or errorCallback, you can modify the content in the response or do some processing.
For example, if the status code of the response is 404, you can display a friendly 404 interface.
If you don't want to use Lambda function writing, you can use civilian writing:
(function(request, next) { // ... // Processing logic before request sending // ... next(function(response) { // ... // Processing logic after request sending // ... // Depending on the request status, the response parameter will be returned to successCallback or errorCallback return response }) })
Example 1
There is a bad user experience in the previous CURD example. If the user uses some functions, if the network is slower and the screen does not provide feedback, the user does not know whether his operation is successful or failed, and he does not know whether he should continue to wait.
Through inteceptor, we can add a loading for all request processing: display loading before the request is sent, and hide loading after receiving the response.
The specific steps are as follows:
1. Add a loading component
<template > <div class="loading-overlay"> <div class="sk-three-bounce"> <div class="sk-child sk-bounce1"></div> <div class="sk-child sk-bounce2"></div> <div class="sk-child sk-bounce3"></div> </div> </div> </template>
2. Use the loading component as a child component of another Vue instance
var help = new Vue({ el: '#help', data: { showLoading: false }, components: { 'loading': { template: '#loading-template', } } })
3. Mount the Vue instance to a certain HTML element
<div > <loading v-show="showLoading"></loading> </div>
4. Add interceptor
((request, next) => { = true next((response) => { = false return response }); });
Example 2
When the user stays on the screen for too long, the screen data may be no longer the latest. If the user deletes or modifys a certain piece of data, if the data has been deleted by other users, the server will feedback a 404 error. However, since our put and delete requests do not process errorCallback, the user does not know whether his operation has succeeded or failed.
You ask me why I don't handle errorCallback in every request, it's because I'm lazy. This problem can also be solved through inteceptor.
1. Continue to use the loading component above and add a dialog box under the #help element.
<div > <loading v-show="showLoading" ></loading> <modal-dialog :show="showDialog"> <header class="dialog-header" slot="header"> <h1 class="dialog-title">Server Error</h1> </header> <div class="dialog-body" slot="body"> <p class="error">Oops,server has got some errors, error code: {{errorCode}}.</p> </div> </modal-dialog> </div>
2. Add two attributes to the data option of the help instance
var help = new Vue({ el: '#help', data: { showLoading: false, showDialog: false, errorCode: '' }, components: { 'loading': { template: '#loading-template', } } })
3. Modify the interceptor
((request, next) => { = true next((response) => { if(!){ = = true } = false return response }); });
Summarize
vue-resource is a very lightweight plugin for handling HTTP requests, which provides two ways to handle HTTP requests:
- Use this.$http
- Use or this.$resource
There is no difference between these two methods in essence. Reading the source code of vue-resource, you can find that the second method is implemented based on the first method.
Inteceptor can attach some behavior before and after the request, which means that in addition to the request processing process, other links of the request can be controlled by us.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.