Vue Foundation (VIII): Vue front-end interaction

Time:2021-8-6

one   Vue front end interaction

What are the methods of interface call?

  • Native Ajax
  • Ajax based on jquery
  • Fetch
  • Promise

What are the URL address formats?

  • Traditional URL
  • URL in restful form

1.1 asynchronous

The execution environment of JavaScript is “single thread”

The so-called single thread means that there is only one thread in the JS engine responsible for interpreting and executing JavaScript code, that is, it can only complete one task at a time. After this task is executed, it can execute the next one. It will “block” other tasks. This task can be called the main thread

Asynchronous mode can perform multiple tasks together

Common asynchronous calls in JS

1.2 promise

It mainly solves the problem of asynchronous deep nesting

Provides a concise API to make asynchronous operations easier

Basic use of Vue


  
  
        /*
            1. Promise basic usage
            We use new to build a promise. The promise constructor receives a parameter, which is a function, and passes in two parameters:
            Resolve and reject represent the callback function after successful execution of asynchronous operation and the callback function after failure of asynchronous operation respectively
        */
        var p = new Promise(function(resolve, reject){
        //2. This is used to implement the setTimeout of asynchronous tasks
        setTimeout(function(){
            var flag = false;
            if(flag) {
                //3. Normal conditions
                resolve('hello');
            }else{
                //4. Abnormal conditions
                Reject ('error ');
            }
        }, 100);
    });
        //5 after the promise instance is generated, you can use the then method to specify the callback functions in the resolved state and reject state, and send Ajax requests based on promise. Promise basic API
        //In the then method, you can also directly return data instead of promise object, and you can receive data in the later then
        p.then(function(data){
        console.log(data)
    },function(info){
        console.log(info)
    });

Execution effect:

As long as the flag value in the code is changed to true, hello will be displayed.

one point three   Send Ajax request based on promise

Promise can help us solve the problem of Ajax request execution order, and can modify nested complex code into chain code.

To play Ajax, you need to install node.js and Baidu yourself.

index.js:

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
//Processing static resources
app.use(express.static('public'))
//Processing parameters
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//Settings allow cross domain access to the service
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Headers', 'mytoken');
  next();
});

//Routing
app.get('/data', (req, res) => {
  res.send('Hello World!')
})
app.get('/data1', (req, res) => {
  setTimeout(function(){
    res.send('Hello TOM!')
  },1000);
})
app.get('/data2', (req, res) => {
  res.send('Hello JERRY!')
})

//Start listening
app.listen(3000, () => {
  console.log('running...')
})

Run index.js:

Execution effect:

As you can see, we can easily control the order of multiple Ajax requests.

one point four   Promise common APIs

. then (): get the correct result of asynchronous task

Function return value in thrn parameter:

1. Return promise instance object

The returned instance object will call the next then

2. Return normal value

The returned normal value is passed to the next then and received through the parameters of the function in the then parameter

Basic use of Vue


  
    /*
      The function return value in the then parameter
    */
    function queryData(url) {
      return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            //Handle normal conditions
            resolve(xhr.responseText);
          }else{
            //Handling exceptions
            Reject ('server error ');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
    }
    queryData('http://localhost:3000/data')
      .then(function(data){
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        return new Promise(function(resolve, reject){
          setTimeout(function(){
            resolve(123);
          },1000)
        });
      })
      .then(function(data){
        return 'hello';
      })
      .then(function(data){
        console.log(data)
      })

Effect of execution:

. catch(): get exception information

. finally(): whether it succeeds or not will be executed (not a formal standard)

Basic use of Vue


  
    /*
      Promise common API instance methods
    */
    // console.dir(Promise);
    function foo() {
      return new Promise(function(resolve, reject){
        setTimeout(function(){
          // resolve(123);
          reject('error');
        }, 100);
      })
    }
    // foo()
    //   .then(function(data){
    //     console.log(data)
    //   })
    //   .catch(function(data){
    //     console.log(data)
    //   })
    //   .finally(function(){
    //     console.log('finished')
    //   });

    // --------------------------
    //The two expressions are equivalent
    foo()
      .then(function(data){
        console.log(data)
      },function(data){
        console.log(data)
      })
      .finally(function(){
        console.log('finished')
      });

Effect of execution:

 

.all():
The promise.all method accepts an array as a parameter, and the objects (P1, P2, P3) in the array are promise instances (if it is not a promise, this item will be converted to a promise with promise.resolve). Its state is determined by these three promise instances.
.race():
The promise.race method also accepts an array as a parameter. When the state of one instance in P1, P2 and P3 changes (becomes fully or rejected), the state of P changes accordingly. And pass the return value of the promise that changes the state first to the callback function of P.

index.js:

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
//Processing static resources
app.use(express.static('public'))
//Processing parameters
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//Settings allow cross domain access to the service
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Headers', 'mytoken');
  next();
});

app.get('/a1', (req, res) => {
  setTimeout(function(){
    res.send('Hello TOM!')
  },1000);
})
app.get('/a2', (req, res) => {
  setTimeout(function(){
    res.send('Hello JERRY!')
  },2000);
})
app.get('/a3', (req, res) => {
  setTimeout(function(){
    res.send('Hello SPIKE!')
  },3000);
})

//Start listening
app.listen(3000, () => {
  console.log('running...')
})

HTML code:

Basic use of Vue


  
    /*
      Promise common API object methods
    */
    // console.dir(Promise)
    function queryData(url) {
      return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            //Handle normal conditions
            resolve(xhr.responseText);
          }else{
            //Handling exceptions
            Reject ('server error ');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
    }

    var p1 = queryData('http://localhost:3000/a1');
    var p2 = queryData('http://localhost:3000/a2');
    var p3 = queryData('http://localhost:3000/a3');
    //The parameters [P1, P2, P3] in all correspond to the returned results one by one ["Hello Tom", "Hello Jerry", "Hello spike"]
//  Promise.all([p1,p2,p3]).then(function(result){
//    console.log(result)
//  })
    Promise.race([p1,p2,p3]).then(function(result){
        //Since P1 executes faster, promise's then() will get the result 'P1'. P2 and P3 are still executing, but the execution results will be discarded.
      console.log(result)
    })

Execution effect:

There is the implementation of all

1.5 Fetch

Fetch API is a new Ajax solution. Fetch returns promise

Fetch is not a further encapsulation of Ajax, but a native JS without the XMLHttpRequest object.

fetch(url, options).then() 

index.js:

app.get('/fdata', (req, res) => {
  res.send('Hello Fetch!')
})

html:

Basic use of Vue


  
    /*
      Basic usage of fetch API
    */
    fetch('http://localhost:3000/fdata').then(function(data){
      //The text () method is part of the fetch API. It returns a promise instance object to get the data returned in the background
      return data.text();
    }).then(function(data){
      console.log(data);
    })

Execution effect:

1.5.1   HTTP request in fetch API

index.js:

app.get('/books', (req, res) => {
  Res.send ('traditional URL passing parameters! '+ req.query.id)
})
app.get('/books/:id', (req, res) => {
  Res.send ('url transfer parameter in restful form! '+ req.params.id)
})
app.delete('/books/:id', (req, res) => {
  Res.send ('delete request passes parameters! '+ req.params.id)
})
app.post('/books', (req, res) => {
  Res.send ('post request pass parameters! '+ req.body.uname + '---' + req.body.pwd)
})

html:

Basic use of Vue


  
    /*
      Fetch API calls the interface to pass parameters
    */

    //Get parameter passing - Legacy URL
//     fetch('http://localhost:3000/books?id=123', {
//       method: 'get'
//     })
//       .then(function(data){
//         return data.text();
//       }).then(function(data){
//         console.log(data)
//       });

    //The get parameter passes a URL in the form of - restful
//     fetch('http://localhost:3000/books/456', {
//       method: 'get'
//     })
//       .then(function(data){
//         return data.text();
//       }).then(function(data){
//         console.log(data)
//       });

    //Delete request mode parameter transfer
//     fetch('http://localhost:3000/books/789', {
//       method: 'delete'
//     })
//       .then(function(data){
//         return data.text();
//       }).then(function(data){
//         console.log(data)
//       });

    //Post request parameter transfer
       fetch('http://localhost:3000/books', {
         method: 'post',
         body: 'uname=lisi&pwd=123',
         headers: {
           'Content-Type': 'application/x-www-form-urlencoded'
         }
       })
         .then(function(data){
           return data.text();
         }).then(function(data){
           console.log(data)
         });

Execution effect:

1.5.2 response format in fetch API

Fetch is used to obtain data. If the response returns normally, the first thing we see is a response object, including a pile of returned original bytes. After receiving these bytes, we need to call methods to convert them into data in corresponding formats, such as JSON, blob or text.

index.js:

app.get('/json', (req, res) => {
  res.json({
    uname: 'lisi',
    age: 13,
    gender: 'male'
  });
})

html:

Basic use of Vue


  
    /*
      Data format of fetch response results
    */
    fetch('http://localhost:3000/json').then(function(data){
      // return data.json(); //  Use JSON to transform the obtained data into an object
      return data.text(); //  Convert the obtained data into a string
    }).then(function(data){
      // console.log(data.uname)
      // console.log(typeof data)
      var obj = JSON.parse(data);
      console.log(obj.uname,obj.age,obj.gender)
    })

Execution effect:

1.6 axios 

Axios (official website:https://github.com/axios/axios)Is an HTTP client based on promise for browsers and node.js.

Support browser and node.js

Promise supported

Can intercept requests and responses

Automatically convert JSON data

Ability to convert request and response data

Download from the official website:

1.6.1 basic usage of Axios

Get and delete requests pass parameters

  • Through the traditional URL? Pass parameters in the form of
  • Pass parameters in restful form
  • Pass parameters in params form

Post and put requests pass parameters

  • Pass parameters through options
  • Pass parameters through urlsearchparams

index.js:

app.get('/adata', (req, res) => {
  res.send('Hello axios!')
})

html:

Basic use of Vue


  
  
    axios.get('http://localhost:3000/adata').then(function(ret){
      //Note that the data attribute is a fixed usage, which is used to obtain the actual data in the background
      // console.log(ret.data)
      console.log(ret)
    })

Execution effect:

 

1.6.2 Axios request parameter transmission

index.js:

app.get('/axios', (req, res) => {
  Res.send ('axios get pass parameter '+ req. Query. ID)
})
app.get('/axios/:id', (req, res) => {
  Res.send ('axios get (restful) pass parameter '+ req. Params. ID)
})
app.delete('/axios', (req, res) => {
  Res.send ('axios get pass parameter '+ req. Query. ID)
})
app.post('/axios', (req, res) => {
  Res.send ('axios post pass parameter '+ req.body.uname +' -- '+ req. Body. PWD)
})
app.put('/axios/:id', (req, res) => {
  Res.send ('axios put pass parameter '+ req.params.id +' -- '+ req.body.uname +' -- '+ req. Body. PWD)
})

html:

Basic use of Vue


  
  
    /*
      Axios request parameter passing
    */
    //Axios get request parameters
    // axios.get('http://localhost:3000/axios?id=123').then(function(ret){
    //   console.log(ret.data)
    // })
    // axios.get('http://localhost:3000/axios/123').then(function(ret){
    //   console.log(ret.data)
    // })
    // axios.get('http://localhost:3000/axios', {
    //   params: {
    //     id: 789
    //   }
    // }).then(function(ret){
    //   console.log(ret.data)
    // })

    //Axios delete request parameters
    // axios.delete('http://localhost:3000/axios', {
    //   params: {
    //     id: 111
    //   }
    // }).then(function(ret){
    //   console.log(ret.data)
    // })

       axios.post('http://localhost:3000/axios', {
         uname: 'lisi',
         pwd: 123
       }).then(function(ret){
         console.log(ret.data)
       })
       var params = new URLSearchParams();
       params.append('uname', 'zhangsan');
       params.append('pwd', '111');
       axios.post('http://localhost:3000/axios', params).then(function(ret){
         console.log(ret.data)
       })

Execution effect:

1.6.3   Axios response results and global configuration

Main attributes of corresponding results:

Data: actual response data

Headers: response header information

Status: response status code

Statustext: response status information

Global configuration information:

Configure common request headers   axios.defaults.baseURL = ‘ https://api.example.com ‘;

Configure timeout   axios.defaults.timeout = 2500;

Configure common request headers   axios.defaults.headers.common[‘Authorization’] = AUTH_ TOKEN;

Configure the content type of public post   axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;

index.js:

app.get('/axios-json', (req, res) => {
  res.json({
    uname: 'lisi',
    age: 12
  });
})

html:

Basic use of Vue


  
  
    /*
      Axios response results and global configuration
    */
   axios.get('http://localhost:3000/axios-json').then(function(ret){
     console.log(ret.data.uname)
   })

    //Configure the base URL address of the request
    axios.defaults.baseURL = 'http://localhost:3000/';
    //Configuration request header information
    axios.defaults.headers['mytoken'] = 'hello';
    axios.get('axios-json').then(function(ret){
      console.log(ret.data.uname)
    })

Execution effect:

 

1.6.4   Axios interceptor

Request Interceptor:

The function of the request interceptor is to perform some operations before the request is sent. For example, a token is added to each request body for unified processing. It is also very easy to change it in the future.

Response Interceptor:

The function of the response interceptor is to perform some operations after receiving the response. For example, when the server returns to the login status and fails and needs to log in again, jump to the login page.

index.js:

app.get('/adata', (req, res) => {
  res.send('Hello axios!')
})

html:

Basic use of Vue


  
  
    /*
      Axios interceptor
    */
//1. Request interceptor
    axios.interceptors.request.use(function(config) {
      console.log(config.url)
//1.1 any request will go through this step. What should be done before sending the request
      config.headers.mytoken = 'nihao';
//1.2 you must return here, otherwise the configuration will not succeed
      return config;
    }, function(err){
      console.log(err)
    })
//2. Response interceptor
    axios.interceptors.response.use(function(res) {
      console.log(res)
//2.1 what to do when receiving a response
      var data = res.data;
      return data;
    }, function(err){
        //2.2 what to do about response errors
      console.log(err)
    })
    axios.get('http://localhost:3000/adata').then(function(data){
      console.log(data)
    })

Execution effect:

 

1.6.5 async and await

Async is placed in front of the function as a keyword

  • Any async function will implicitly return a promise

The await keyword can only be used in functions defined using async

  • Await can be directly followed by a promise instance object
  • The await function cannot be used alone

Async / await makes asynchronous code look and behave more like synchronous code

index.js:

app.get('/async1', (req, res) => {
  res.send('hello1')
})
app.get('/async2', (req, res) => {
  if(req.query.info == 'hello') {
    res.send('world')
  }else{
    res.send('error')
  }
})

html:

Basic use of Vue


  
  
    /*
      Async / await handles asynchronous operations:
      The async function returns a promise instance object
      Await can be directly followed by a promise instance object
    */
    axios.defaults.baseURL = 'http:localhost:3000';
    // axios.get('adata').then(function(ret){
    //   console.log(ret.data)
    // })
    
    // async function queryData() {
    //   var ret = await axios.get('adata');
    //   // console.log(ret.data)
    //   return ret.data;
    // }

        //1. Basic usage of Async
        //1.1 async is put in front of the function as a keyword
    async function queryData() {
        //1.2 await关键字只能在使用async定义的函数中使用 Await can be directly followed by a promise instance object
      var ret = await new Promise(function(resolve, reject){
        setTimeout(function(){
          resolve('nihao')
        },1000);
      })
      // console.log(ret.data)
      return ret;
    }
    //1.3 any async function will implicitly return a promise. We can use then for chain programming
    queryData().then(function(data){
      console.log(data)
    })

Execution effect:

 

html:

Basic use of Vue


  
  
    /*
      Async / await handles multiple asynchronous tasks
    */
        //2. Async function handles multiple asynchronous functions
    axios.defaults.baseURL = 'http://localhost:3000';

    async function queryData() {
        //2.1 after adding await, the following code will not be executed until the current await returns the result
      var info = await axios.get('async1');
      //2.2 make asynchronous code look and behave more like synchronous code
      var ret = await axios.get('async2?info=' + info.data);
      return ret.data;
    }

    queryData().then(function(data){
      console.log(data)
    })

Execution effect: