vue learning Note 6: comparison of network request details of Jquery VS Vue

Catalogue of series articles

Part 1: overview of differences between jQuery and Vue
Part 2: comparison of element operation details of Jquery VS Vue
Part III: comparison of event listening details of Jquery VS Vue
Part IV: comparison of network request details of Jquery VS Vue
Part V: detailed comparison of miscellaneous methods of Jquery VS Vue
Chapter 6: global attribute comparison of Jquery VS Vue
Chapter 7: comparison of traversal methods of Jquery VS Vue
Chapter 8: comparison of page animation details of Jquery VS Vue

1, Foreword

This article summarizes the implementation of network request related methods in jQuery in vue. vue's network requests are supported in multiple ways: ajax, jqueryAjax, fetch, axios, etc. they are not shown if they are familiar with ajax and jaury. This article mainly shows the use of axios. JQuery can also be introduced into vue to realize network requests,
jquery reference documents: jQuery Ajax request
vue reference documents: Vue uses axios to access the APIaxios official website

2, Details

2.1 implementation of event binding method:

methoddescribe
$.ajax()Executing asynchronous AJAX requests
$.ajaxPrefilter()Before each request is sent and is $ Handle custom Ajax options or modify existing options before ajax() processing
$.ajaxSetup()Set default values for future AJAX requests
$.ajaxTransport()Create an object that handles the actual transfer of Ajax data
$.get()Use the HTTP GET request of AJAX to load data from the server
$.getJSON()
$.getScript()Use the HTTP GET request of AJAX to load and execute JavaScript from the server
$.param()Create a serialized representation of an array or object (a URL query string that can be used for AJAX requests)
$.post()Load data from the server using AJAX's HTTP POST request
load()Load data from the server and place the returned data into the specified element

Corresponding implementation in vue:
The usage is similar to jquery. After introducing axios, you can directly use the corresponding method to make network requests. Refer to the documentation Axios instructions
axios installation:

npm install --save axios vue-axios

Introduced into the code:

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

Parameter configuration details:

{
  // `URL ` is the server URL for the request
  url: '/user',

  // `Method ` is the method used when creating the request
  method: 'get', // The default is get

  // `baseURL 'will be automatically added before' URL ', unless' URL' is an absolute URL.
  // It can set a 'baseURL' to facilitate the delivery of relative URL s for axios instance methods
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest ` allows you to modify the request data before sending it to the server
  // It can only be used in the request methods of 'PUT', 'POST' and 'PATCH'
  // The function in the following array must return a string, or ArrayBuffer, or Stream
  transformRequest: [function (data) {
    // Arbitrary conversion of data

    return data;
  }],

  // `transformResponse ` it is allowed to modify the response data before passing it to then/catch
  transformResponse: [function (data) {
    // Arbitrary conversion of data

    return data;
  }],

  // `headers ` is the custom request header to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params ` is the URL parameter to be sent with the request
  // Must be a plain object or URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer ` is a function responsible for 'params' serialization
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `Data ` is the data sent as the request body
  // Only applicable to these request methods' put ',' post ', and' PATCH '
  // When 'transformRequest' is not set, it must be one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // -Browser specific: FormData, File, Blob
  // -Node exclusive: Stream
  data: {
    firstName: 'Fred'
  },

  // `Timeout of the specified request in milliseconds (no timeout)
  // If the call cost exceeds the 'timeout', the request will be interrupted
  timeout: 1000,

  // `withCredentials ` indicates whether credentials are required for cross domain requests
  withCredentials: false, // default

  // `adapter ` allows custom processing of requests to make testing easier
  // Return a promise and apply a valid response (see [response docs] (#response API))
  adapter: function (config) {
    /* ... */
  },

  // `auth ` indicates that HTTP basic authentication should be used and credentials should be provided
  // This will set an 'Authorization' header, overwriting any existing custom 'Authorization' header set with 'headers'
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType ` indicates the data type of the server response. It can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `Xsrfcookie name ` is the name of the cookie used as the value of xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName ` is the name of the HTTP header that carries the value of xsrf token
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress ` allows processing progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Handling of native progress events
  },

  // `onDownloadProgress ` allows processing progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Handling of native progress events
  },

  // `maxContentLength ` defines the maximum size of the allowed response content
  maxContentLength: 2000,

  // `validateStatus ` defines whether the status code for a given HTTP response is resolve or reject promise. If 'validateStatus' returns' true' (or set to 'null' or 'undefined'), promise will be resolved; Otherwise, promise will be rejecte d
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects ` is defined in node The maximum number of redirects of follow in JS
  // If set to 0, no redirection will follow
  maxRedirects: 5, // default

  // `httpAgent 'and' httpsAgent 'are on node JS is used to define the custom proxy used when executing http and https. Allow options to be configured like this:
  // `keepAlive ` is not enabled by default
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the host name and port of the proxy server
  // `auth ` indicates that HTTP basic authentication should be used for connection proxy and provide credentials
  // This will set a 'proxy authorization' header, overwriting the existing custom 'proxy authorization' header set by using 'header'.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: : {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken ` specifies the cancel token used to cancel the request
  // (see the Cancellation section later for more information)
  cancelToken: new CancelToken(function (cancel) {
  })
}

The request name corresponds to jquery:

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

Base GET request:

// Create request for user with given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Basic POST request:

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

2.2 realization of network request events:

methoddescribe
ajaxComplete()Specifies the function to run when the AJAX request completes
ajaxError()Specifies the function to run when an AJAX request fails
ajaxSend()Specifies the function to run before the AJAX request is sent
ajaxStart()Specifies the function to run at the beginning of the first AJAX request
ajaxStop()Specifies the function to run when all AJAX requests are completed
ajaxSuccess()Specifies the function to run when the AJAX request completes successfully

Corresponding implementation in vue:

// `transformRequest ` allows you to modify the request data before sending it to the server
  // It can only be used in the request methods of 'PUT', 'POST' and 'PATCH'
  // The function in the following array must return a string, or ArrayBuffer, or Stream
  transformRequest: [function (data) {
    // Arbitrary conversion of data

    return data;
  }],

  // `transformResponse ` it is allowed to modify the response data before passing it to then/catch
  transformResponse: [function (data) {
    // Arbitrary conversion of data

    return data;
  }],
  // `adapter ` allows custom processing of requests to make testing easier
  // Return a promise and apply a valid response (see [response docs] (#response API))
  adapter: function (config) {
    /* ... */
  },
   // `onUploadProgress ` allows processing progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Handling of native progress events
  },

  // `onDownloadProgress ` allows processing progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Handling of native progress events
  },

2.3 tool and method realization:

methoddescribe
serialize()Encode the set of form elements as strings for submission
serializeArray()Encode an array of names and values for the form element set

Corresponding implementation in vue:

// `paramsSerializer ` is a function responsible for 'params' serialization
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

3, Summary

This article summarizes the implementation methods of network requests and other corresponding vue s in jquery.

Keywords: Front-end Vue.js Ajax

Added by slshmily on Wed, 02 Mar 2022 14:37:39 +0200