The growth path of Lenhart - Vue Ajax

Lenhart's growth path -- Vue Ajax

1. Solution of callback function promise class

Before I talk about ajax, let me start with the callback function. The so-called callback function is to import the subsequent processing logic into the current thing to do. After doing the job, call this function and implement an example of buying vegetables below.

let a = '';
function buy(callback) {
    setTimeout(()=>{
        a = 'Mushroom';
        callback(a);
    }, 2000);
}
buy(function cookie(val) {
    console.log(val);
});

Promise is used to solve the callback problem. The instance of promise is a then method, which has two parameters, resolve and reject,
Here are the three states of promise (it will be executed directly when parameters are not passed)

  • The resolve function will be called in the full success state
  • Reject function will be called when reject fails
  • wait state

Then use promise to solve the above shopping methods:

let promise = new Promise((resolve, reject)=>{
    setTimeout(() => {
        let a = 'Mushroom';
        // resolve(a);
        reject();
    }, 2000);
});
promise.then((data)=>{console.log(data)}, (err)=>{console.log('err')})

Next, use promise to write a coin throwing function to buy a bag for your girlfriend:

function buyPack() {
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            if (Math.random()>0.5){
                resolve('Buying bags');
            } else {
                reject('Not buy');
            }
        }, Math.random()*3000); // 3Make a decision in seconds, you know

    })
}
buyPack().then((data)=>{
    console.log(data);
}, ()=>{
    console.log(data);
});

2. Use promise to encapsulate asynchronous Ajax promise Ajax

First, I create a cart.json file to hold the json data.

[
  {
    "isSelected": true,
    "productCover": "123",
    "productName": "Explain profound theories in simple language Node.js Study",
    "productInfo": "Explain profound theories in simple language Node.js Study,Explain profound theories in simple language Node.js Study",
    "productPrice": 45.5,
    "productCount": 1
  },
  {
    "isSelected": true,
    "productCover": "345",
    "productName": "javascript Data structure and algorithm",
    "productInfo": "javascript Data structure and algorithm,javascript Data structure and algorithm",
    "productPrice": 49.5,
    "productCount": 1
  }
]

Then we create a file of promise-ajax.js, and encapsulate Ajax with promise method, then we can use it

/**
 * promise-ajax
 * @param url
 * @param type
 * @param dataType
 * @returns {Promise<any>}
 */
function ajax({url='', 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.onReadyState === 4 && xhr.status === 200
            resolve(xhr.response);  //Successful method call
        };
        xhr.onerror = function (err) {
            reject(err);            //Failed call failed method
        }
        xhr.send();
    });
}

3. Implement the encapsulated ajax method in vue

I am using webstorm's server. Next, I use vue's method to request the cart.json file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue-ajax</title>
</head>
<body>
<div id="app">
    {{arr}}
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./4.promise-ajax.js"></script>
<script>

    let vm = new Vue({
        el: '#app',
        //A special way to send ajax
        created(){
            ajax({url:'./cart.json'}).then((res)=>{
                console.log(res);
            }, (err)=>{
                //...
            })
        },
        method:{
            a:''
        },
        data: {
            arr:[],
            products:[]
        }
    });
</script>
</body>
</html>

Then you can see the data request coming back in chrome's developer tools.

Tags: Vue JSON Javascript

Posted on Tue, 14 Apr 2020 08:11:19 -0700 by dyluck