Front small white simple summary, reference to the black horse Everest and other courses and other content integration, also hope you big guy more to teach ~

Use of Axios

Axios is a Promise-based HTTP client for browsers and NodeJS. It’s essentially an encapsulation of native XHR, but it’s an implementation of Promise that complies with the latest ES specification and has the following features:

  • Create XMLHttpRequests from the browser
  • Create an HTTP request from Node.js
  • Supporting Promise API
  • Intercept requests and responses
  • Transform request data and response data
  • Cancel the request
  • Automatically convert JSON data
  • The client supports XSRF defense

In short, ajax is wrapped around promises

The basic use of VUE is as follows:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="node_modules/vue/dist/vue.js"></script>
<script src="node_modules/axios/dist/vue.js"></script>

<script>
  let vm = new Vue({
    el: '#app'.created(){ // This is called after the data has been initialized. This also refers to the VM instance
      this.getData();
    },
    data: {
      products: []},methods: {
      getData(){ // Initialize the method
        // The method used specifically to send Ajax
        // This in the callback refers to window, so use the arrow function
        // Promise to fix the callback problem
        axios.get('./cart.json').then(res= > { // success
          this.products = res.data; // Res.data is needed to get the data
        },err= > { // error
          console.log(err); }); }}})</script>
</body>
</html>
Copy the code

Two, Promise principle

Until a Promise is made, the data will be returned to you at some point in time. Asynchronous operations are handled with callbacks.

Callback function: pass subsequent processing logic to the current thing to be done, and call this function when the thing is done

// Cook -> buy food
// Pass the subsequent cooking to the grocery store
function buy(callback) {
  setTimeout(() = > {
    let a = 'mushroom';
    callback(a)
  }, 2000);
}
buy(function cook(val) {
  console.log(a);
});
Copy the code

PromiseIt is designed to solve callback problems and avoid the “callback hell” of nested functions, which can seriously affect code readabilityPromiseThere are three states:Success, failure, and waitAmong them,resolveIt stands for turnSuccessful state rejectIt stands for turnFailure state resolveandReject **** are both functions PromiseThe most basic example isthenMethod,thenThere are two parameters in the method, which are twofunctionThe first function is atPromiseTurn toresolveThe method that executes the second function is inPromiseTurn torejectMethod of execution

let p = new Promise((resolve, reject) = > {
  setTimeout(function () {
      let a = 'mushroom';
      resolve(a);
      reject(a);
  }, 2000)}); p.then((data) = > {console.log(data)}, (err) = > {console.log(err)});
Copy the code

Example: buying a bag

function buyPack() {
  return new Promise((resolve, reject) = > {
      setTimeout(() = > {
          if(Math.random()>0.5){
            resolve('buy')}else{
            reject('don't buy')}},Math.random() * 1000);
  });
}
buyPack().then(function (data) {
  console.log(data);
}, function (data) {
  console.log(data);
});
Copy the code

3. Manually encapsulate AJAX based on promises

/* 4.promise-ajax.js */
function ajax({url='xxx', type="get", dataType="json"}) {

  return new Promise((resolve, reject) = > {
    let xhr = new XMLHttpRequest();
    xhr.open(type, url, true);
    xhr.responseType = dataType;
    xhr.onload = function () { // xhr.readState=4 xhr.status=200
      if(xhr.status == 200){
        resolve(xhr.response) // Call the successful method successfully
      }else{
        reject('not found'); }}; xhr.onerror =function (err) {
        reject(err) // Failed to call the failed method}; xhr.send(); })}Copy the code

Call:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <div id="app"></div>
  <script src="node_modules/vue/dist/vue.js"></script>
  <script src="4.promise-ajax.js"></script>
  <script>
    let vm = new Vue({
      el: '#app'.created(){
        ajax({url: './carts.json'}).then((res) = >{
          console.log(res)
        }, (err) = >{
          console.log(err)
        })
      },
      data: {
        products: []}})</script>
</body>
</html>
Copy the code