Zero: Interaction with the backend – Ajax

Version 1 – Cross-domain issues have occurred

Front end: index. HTML

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue interacts with the back end - cross domain issues have occurred</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <button @click="handleClick">Load the data</button>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box'.data: {},
        methods: {
            handleClick() {
                $.ajax({
                    url: 'http://127.0.0.1:5000/'.// The url to send the request, local port 5000, is flask's default port
                    method: 'get'.success: (data) = > {
                        console.log(data)
                    }
                })
            }
        }
    })
</script>
</html>
Copy the code

The backend: main py

from flask import Flask	This is tested using the lightweight Flask framework

app = Flask(__name__)


@app.route('/')
def index() :
    print('Here comes the request')
    return 'Hello World'


if __name__ == '__main__':
    app.run()
Copy the code

Here you can see that the front end successfully sent the request to the back end, and the back end successfully responded, but the front end reported an error

This is because of a cross-domain problem where the browser detects that the front end and back end are not from the same domain and considers this to be insecure, so it blocks the transfer of the resource

To solve this problem, implement: CORS, or cross-domain resource sharing

Version 2 – Resolves cross-domain issues

Front end: index. HTML

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue interacts with the back end - resolves cross-domain issues</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <button @click="handleClick">Load the data</button>
    <p>Load data: {{myText}}</p>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box'.data: {
            myText: ' '
        },
        methods: {
            handleClick() {
                $.ajax({
                    url: 'http://127.0.0.1:5000/'.method: 'get'.success: (data) = > {
                        console.log(data)
                        this.myText = data
                    }
                })
            }
        }
    })
</script>
</html>
Copy the code

The backend: main py

from flask import Flask, make_response

app = Flask(__name__)


@app.route('/')
def index() :
    print('Here comes the request')
    res = make_response('Hello World')
    res.headers['Access-Control-Allow-Origin'] = The '*'	Access control allows all sources to be set
    return res


if __name__ == '__main__':
    app.run()
Copy the code

Version 3 – The backend reads json files to the front-end

Json file: file.json

{
  "name": "Darker"."age": "18"."gender": "male"
}
Copy the code

Front end: index. HTML

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue and back-end interaction - JSON</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <button @click="handleClick">Load the data</button>
    <p>Load data: {{myText}}</p>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box'.data: {
            myText: ' '
        },
        methods: {
            handleClick() {
                $.ajax({
                    url: 'http://127.0.0.1:5000/'.method: 'get'.success: (data) = > {
                        console.log(data)
                        this.myText = data
                    }
                })
            }
        }
    })
</script>
</html>
Copy the code

The backend: main py

import json

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/')
def index() :
    print('Here comes the request')
    with open('file.json', mode='rt', encoding='utf-8') as f:
        dic = json.load(f)
    res = jsonify(dic)
    res.headers['Access-Control-Allow-Origin'] = The '*'
    return res


if __name__ == '__main__':
    app.run()
Copy the code

A: fetch

1. Introduction

(1) introduce the fetch

Provides a JavaScript interface for accessing and manipulating specific parts of the HTTP pipeline, such as requests and responses

It also provides a global fetch() method, which provides a simple, reasonable way to fetch resources asynchronously across a network

② Fetch basic format

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });
Copy the code

Example 2.

Json file: file.json

{
  "name": "Darker"."age": "18"."gender": "male"
}
Copy the code

The backend: main py

import json

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/')
def index() :
    print('Here comes the request')
    with open('file.json', mode='rt', encoding='utf-8') as f:
        dic = json.load(f)
    res = jsonify(dic)
    res.headers['Access-Control-Allow-Origin'] = The '*'
    return res


if __name__ == '__main__':
    app.run()
Copy the code

Front end: index. HTML

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue interacts with the backend - FETCH</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <button @click="handleClick">Load the data</button>
    <p>Loaded data:</p>
    <ul>
        <li >Name: {{name}}</li>
        <li >Age: {{age}}</li>
        <li >Gender: {{gender}}</li>
    </ul>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box'.data: {
            name:' '.age: ' '.gender: ' '
        },
        methods: {
            handleClick() {
                fetch('http://127.0.0.1:5000/').then(response= > {
                    return response.json()
                }).then(json= > {
                    console.log('JSON data retrieved from the back end', json)   // The data obtained by success
                    this.name = json.name
                    this.age = json.age
                    this.gender = json.gender
                }).catch(ex= > {
                    console.log('An exception has occurred.', ex)    // Throw an exception}}}})</script>
</html>
Copy the code

2: Axios

1. Introduction

Axios is a Promise-based HTTP library that can be used in browsers and Node.js

② Axios official website:www.axios-js.com/

Example 2.

Json file: film.json (this is just part of it, too much original code…)

{
    "data": {"films":[
            {
                "actors":[
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/45deca0f886633f1a8902f7eece4248a.jpg"."name":Dante Lam."role":"Director"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/ff8f5bfd455e660298452c0546bb23d5.jpg"."name":"Xin Zhi Lei"."role":"Fang Yuling"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/f27b94579d10d3131b476ec6c63a2722.jpg"."name":"Blue Ying Ying"."role":"Actor"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/0a30de65731f3ddc5ce5d5915c8d9d49.jpg"."name":"Eddie Peng"."role":"Gao"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/728944e292dc6e8161acd7d5344d361c.jpg"."name":"Wang Yanlin"."role":"Zhao is"}]."category":"Plot | disaster"."director":Dante Lam."filmId":4836."filmType": {"name":"2D"."value":1
                },
                "grade":"7.8"."isPresale":true."isSale":false."item": {"name":"2D"."type":1
                },
                "language":"Mandarin Chinese"."name":"Emergency rescue"."nation":"Mainland China"."poster":"https://pic.maizuo.com/usr/movie/c14a70858e2bda9c2bc8eaa7bfa0e2aa.jpg"."premiereAt":1579910400."runtime":100."synopsis":"Emergency" is China's first maritime salvage film directed by Dante Lam and starring Eddie Peng, Wang Yanlin, Xin Zhilei and LAN Yingying. Preparation process, field survey and site director Dante lam lead the team, strive to create more explosive, more thrilling scene Settings, this Peter pau and the Oscar for best photography, "Titanic" art director Martin Laing and other international top combination of the production team, heralds the film will be the first to open the international market of Chinese relief paintings, It will surely become another benchmark for Chinese films."."timeType":3."videoId":"XNDIyODM2NjE4OA=="
            },
            {
                "actors":[
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/c8722df42d08942db01c2a262f576950.jpg"."name":Yi Xiaoxing."role":"Director"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/9627d1ebac2b4b12a06fd1623a62af99.jpg"."name":"Peng Yuchang"."role":"XiaoXiang"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/4b6da2deabe5dc7883321bb17372c25b.jpg"."name":"Qiao Sha"."role":"Zhou Donghai"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/7efe813dd79280f236b8d1286cdc313c.jpg"."name":"Buguan Jin"."role":"Zhou Xixi"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/f244a95cdcd64625a50069bd64db49c2.jpg"."name":"WeiQing"."role":"Sufen Wang"}]."category":"Comedy | action"."director":Yi Xiaoxing."filmId":5266."filmType": {"name":"2D"."value":1
                },
                "grade":"7.2"."isPresale":true."isSale":false."item": {"name":"2D"."type":1
                },
                "language":""."name":"The Bathing King."."nation":"Mainland China"."poster":"https://pic.maizuo.com/usr/movie/e6aabffd040bda24f483bcc95ed79e62.jpg"."premiereAt":1607644800."runtime":102."synopsis":"In rub bath service, rich 2 acting Xiao Xiang (Peng Yuchang is acted the role of) and rub zao worker Zhou Donghai (Qiao Shan is acted the role of) produce contradiction, let Zhou Donghai face predicament of life. Xiao Xiang was sent to the hospital because of parachuting accident memory is lost, Zhou Donghai happens to bump into, the heart gives birth to a plan, cheat Xiao Xiang is his brother and cheat back to zhou Home bathhouse when rub zao work, then a rich 2 generation began a paragraph of lifelong unforgettable rub zao career..."."timeType":3."videoId":""
            },
            {
                "actors":[
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/168e82b3c4ec676ca577cb99e5a9ee06.jpg"."name":"Patty Jenkins."."role":"Director"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/c4cfadaaab8f81ebaf3bdc7aa30fac49.jpg"."name":"Gal Gadot."."role":"Diana Prince/Wonder Woman"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/6e0a82c6efac00bfb6b7c1b4bb46eaa9.jpg"."name":"Chris Pine."."role":"Steve Trevor."
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/79a97235ee2f33741b63eafc2f34658e.jpg"."name":"Kristen Wiig."."role":8. "Barbara Minerva Cheetah"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/13c53574fc0c4b13b99e966af5af7e9d.jpg"."name":"Pedro PASCAL."."role":"马克斯维尔·劳德 Max Lord"}]."category":"Action | fantasy | adventure"."director":"Patty Jenkins."."filmId":5287."filmType": {"name":"3D"."value":2
                },
                "isPresale":true."isSale":false."item": {"name":"3D"."type":2
                },
                "language":""."name":"Wonder Woman 1984"."nation":"The United States." "."poster":"https://pic.maizuo.com/usr/movie/4f84f5a48560f5b14b0fac7768da4e05.jpg"."premiereAt":1608249600."runtime":151."synopsis":"Wonder Woman's new big-screen adventure arrives in the 1980s. Diana Wonder Woman lives a normal life at Washington's Museum of Natural History, but everything changes after she fosters a seemingly ordinary robbery. Under the temptation of powerful divine power, two new strong enemies quietly appear -- and wonder Woman "love each other to kill" top predator leopard female, and control the power to change the world Max · Lord, a startling war is inevitable. On the other hand, old love Steve has suddenly returned from the dead to rekindle his love affair with Diana, but the romantic touch of Steve's return is also in doubt.."timeType":3."videoId":""
            },
            {
                "actors":[
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/6735332cb677645542c2f136eb37e561.jpg"."name":"Lai Tao Yau"."role":"Director"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/ca47cd961fe0be0c91149f6bcca2f13d.jpg"."name":"Andy Lau"."role":"Pan rides the Wind"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/82a5d97e318c447133cd6c8262cee846.jpg"."name":"Liu Ching-wan"."role":"Dong Cheuk-man"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/e776871fe75f0367aa60957457a6f96c.jpg"."name":"NiNi"."role":"PangLing"
                    },
                    {
                        "avatarAddress":"https://pic.maizuo.com/usr/movie/dd120eb1f6bda9f3b9c9e4c49785d0ce.jpg"."name":"Xie Junhao"."role":"Actor"}]."category":"Action | crime"."director":"Lai Tao Yau"."filmId":5257."filmType": {"name":"2D"."value":1
                },
                "isPresale":true."isSale":false."item": {"name":"2D"."type":1
                },
                "language":""."name":"Bomb Disposal Expert 2"."nation":"Mainland China, Hong Kong, China"."poster":"https://pic.maizuo.com/usr/movie/4a2bec5290b94f7eb597913727b21df6.jpg"."premiereAt":1608768000."runtime":0."synopsis":A bomb explodes in Hong Kong, and former bomb disposal expert Pan Chengfeng (Andy Lau) is in a coma at the scene. The Pan after wake up by wind can escape at the same time to find out the truth at the same time, however, his good friend Dong Zhuowen (Liu Qingyun is acted the role of) and his ex-cummer Pang Ling (Ni Ni is acted the role of) told about two quite different experiences to him however. Planned bombings happen one after another, the truth is more and more confusing..."."timeType":3."videoId":""}]."total":47
    },
    "msg":"ok"."status":0
}
Copy the code

The backend: main py

import json

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/film')
def index() :
    print('Here comes the request')
    with open('film.json', mode='rt', encoding='utf-8') as f:
        dic = json.load(f)
    res = jsonify(dic)
    res.headers['Access-Control-Allow-Origin'] = The '*'
    return res


if __name__ == '__main__':
    app.run()

Copy the code

Front end: index. HTML

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The Vue interacts with the back end</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.min.js"></script>
</head>
<body>

<div id="box">
    <button @click="handleClick">Loading movie Data</button>
    <p>Loaded data:</p>
    <ul>
        <li v-for="item in dataList">
            <p>. Movie: {{item name}}</p>
            <p>Director: {{item. Director}}</p>
            <img :src="item.poster" alt="">
        </li>

    </ul>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#box'.data: {
            dataList: []},methods: {
            handleClick() {
                axios.get("http://127.0.0.1:5000/film/").then(res= > {
                    console.log(res.data.data.films) // Axios automatically wraps the data attribute res.data
                    this.dataList = res.data.data.films
                }).catch(err= > {
                    console.log(err); }}}})</script>
</html>
Copy the code

Three: calculate attributes

Computed properties are cached based on their dependencies

A calculated property is reevaluated only if its associated dependencies change

Evaluating properties, like properties in Python, can disguise methods/functions as properties

1. Capitalize the first letter of the name by calculating the property

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Uppercase</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <! -- A large chunk of code is not good to write here, use computed properties -->{{mytext.substring (0,1).touppercase ()+ mytext.substring (1)}}<p>{{getNameMethod()}}</p>
    <! The difference is that the calculated properties are used multiple times in the same page, and not executed multiple times.
    <p>Calculate attributes: {{getName}}</p>
    <! -- Normal method uses parentheses -->

</div>
</body>
<script>
    var vm = new Vue({
        el: '#box'.data: {
            myText: 'darker',},computed: {
            getName() { // The dependency state changes and is recalculated
                return this.myText.substring(0.1).toUpperCase() + this.myText.substring(1)}},methods: {
            getNameMethod() {
                return this.myText.substring(0.1).toUpperCase() + this.myText.substring(1)}}})</script>
</html>
Copy the code

2. Rewrite filtering cases by calculating attributes

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Override filtering cases by calculating attributes</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <p><input type="text" v-model="myText" placeholder="Please enter what to filter:"></p>
    <ul>
        <li v-for="data in newList">{{data}}</li>
    </ul>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box'.data: {
            myText: ' '.dataList: ['a'.'at'.'atom'.'be'.'beyond'.'cs'.'csrf'],},computed: {
            newList() {
                return this.dataList.filter(item= > {
                    return item.indexOf(this.myText) > -1   // return elements with an index greater than 1: >-1 indicates inclusion}}}})</script>
</html>
Copy the code

Four: the role of virtual DOM and diff algorithm key

1. What is the use of key in vue2.0V-for?

Not only vue, React also requires a key to be added to each component when performing list rendering

A key is a unique identifier, just like an ID

Remember that both Vue and React implement a virtual DOM that allows you to re-render pages by manipulating data rather than directly manipulating DOM elements

The underlying principle is its efficient Diff algorithm

  • Comparison by level: Only compare at the same level
  • Compare by key value: Insert new keys into the same group (loop, add as much as possiblekey, make key unique)
  • Compare by component/label: then replace

2. Diff algorithm of virtual DOM

Virtual DOM data rendering diagram

3. Implementation

① Divide the tree into layers

② Compare by key value

③ Compare by component

<div id="box">
    <div v-if="isShow">111</div>
    <p v-else>222</p>
    <! -- {tag:div,value:111} {tag:p,value:222}

    <div v-if="isShow">111</div>
    <div v-else>222</div>
    <! -- {tag:div,value:111} {tag:div,value:222}
</div>
Copy the code

Consider: What is a cross-domain problem? How to solve it?