Rapid development of grain mall VUE

Posted by dechamp on Sun, 19 Dec 2021 02:04:54 +0100

This article is a personal note to deepen your impression. Please see the original author's article
Original link: https://blog.csdn.net/hancoder/article/details/107007605

1, ES6

ECMAScript is a standard javascript implementation

VS environment construction

As I wrote before, you need to install the following plug-ins in VScode:

Auto Close Tag
Auto Rename Tag
Chinese
ESlint
HTML CSS Support
HTML Snippets
JavaScript ES6
Live Server
open in brower
Vetur33
Vue 2Snippets syntax tips
Install the plug-in Vue Devtools in Google browser

1, New features of ES6

Open VSCode - Open Folder - New es6 folder - new file 1. Let html—shift+!+Enter to generate the template.

1.1 use of let and const variables

let Will not affect{}Outside, var Will jump across the domain to{}Outside
var You can declare the same variable multiple times, let Will report an error
var Can be used before definition, let Cannot be used before definition. (variable lifting problem)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    

    <script>
       // Variables declared by var tend to cross domain
       // let declared variables have strict local scope
         {
             var a = 1;
             let b = 2;
         }
         console.log(a);  // 1
         console.log(b);  // ReferenceError: b is not defined

         // var can be declared multiple times
         // let can only be declared once
         var m = 1
         var m = 2
         let n = 3
//         let n = 4
         console.log(m)  // 2
         console.log(n)  // Identifier 'n' has already been declared

        // var variable promotion
        // There is no variable promotion
         console.log(x);  // undefined
         var x = 10;
         console.log(y);   //ReferenceError: y is not defined
         let y = 20;

        // let
        // 1. The const statement cannot be changed
           // 2. Once declared, it must be initialized, otherwise an error will be reported
        const a = 1;
        a = 3; //Uncaught TypeError: Assignment to constant variable.
    
    </script>

</body>
</html>

1.2 deconstruction expression

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <script>
        //Array deconstruction
        let arr = [1,2,3];
        // // let a = arr[0];
        // // let b = arr[1];
        // // let c = arr[2];

        let [a,b,c] = arr;
        console.log(a,b,c)

        const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }
        //         const name = person.name;
        //         const age = person.age;
        //         const language = person.language;

        //Object deconstruction / / change the name attribute to abc and declare three variables: abc, age and language
        const { name: abc, age, language } = person;
        console.log(abc, age, language)

        //4. String extension
        let str = "hello.vue";
        console.log(str.startsWith("hello"));//true
        console.log(str.endsWith(".vue"));//true
        console.log(str.includes("e"));//true
        console.log(str.includes("hello"));//true

        //String template ` ` you can define multiple lines of strings
        let ss = `<div>
                    <span>hello world<span>
                </div>`;
        console.log(ss);
        
        function fun() {
            return "This is a function"
        }

        // 2. String inserts variables and expressions. Variable names are written in ${}, and JavaScript expressions can be placed in ${}.
        let info = `I am ${abc},this year ${age + 10}Yes, I want to say: ${fun()}`;
        console.log(info);

    </script>
</body>
</html>

1.3 optimization of function parameters

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <script>
        //Before ES6, we could not set the default value for a function parameter, but could only use the alternative:
        function add(a, b) {
            // Judge whether b is empty. If it is empty, the default value is 1
            b = b || 1;
            return a + b;
        }
        // Pass a parameter
        console.log(add(10));


        //Now it can be written as follows: write the default value directly to the parameter, and the default value will be used automatically if it is not passed
        function add2(a, b = 1) {
            return a + b;
        }
        console.log(add2(20));


        //2) . indefinite parameters
        function fun(...values) {
            console.log(values.length)
        }
        fun(1, 2)      //2
        fun(1, 2, 3, 4)  //4

        //3) , arrow function. lambda
        //Previously declared a method
        // var print = function (obj) {
        //     console.log(obj);
        // }
        var print = obj => console.log(obj);
        print("hello");

        var sum = function (a, b) {
            c = a + b;
            return a + c;
        }

        var sum2 = (a, b) => a + b;
        console.log(sum2(11, 12));

        var sum3 = (a, b) => {
            c = a + b;
            return a + c;
        }
        console.log(sum3(10, 20))


        const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }

        function hello(person) {
            console.log("hello," + person.name)
        }

        //Arrow function + deconstruction
        var hello2 = ({name}) => console.log("hello," +name);
        hello2(person);

    </script>
</body>
</html>

1.4 object optimization

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }

        console.log(Object.keys(person));//["name", "age", "language"]
        console.log(Object.values(person));//["jack", 21, Array(3)]
        console.log(Object.entries(person));//[Array(2), Array(2), Array(2)]

        const target  = { a: 1 };
        const source1 = { b: 2 };
        const source2 = { c: 3 };

        // merge
        //{a:1,b:2,c:3}
        Object.assign(target, source1, source2);

        console.log(target);//["name", "age", "language"]

        //2) . abbreviation of declaration object
        const age = 23
        const name = "Zhang San"
        const person1 = { age: age, name: name }
        // Equivalent to
        const person2 = { age, name }//Declaration object abbreviation
        console.log(person2);

        //3) Function attribute abbreviation of object
        let person3 = {
            name: "jack",
            // Previously:
            eat: function (food) {
                console.log(this.name + "Eating" + food);
            },
            //The arrow function this cannot be used. To use it, you need to use: object attribute
            eat2: food => console.log(person3.name + "Eating" + food),
            eat3(food) {
                console.log(this.name + "Eating" + food);
            }
        }

        person3.eat("Banana");
        person3.eat2("Apple")
        person3.eat3("a mandarin orange");

        //4) , object extension operator

        // 1. Copy object (deep copy)
        let p1 = { name: "Amy", age: 15 }
        // Indicates that all attributes in p1 are assigned to someone
        let someone = { ...p1 }
        console.log(someone)  //{name: "Amy", age: 15}

        // 2. Merge objects
        let age1 = { age: 15 }
        let name1 = { name: "Amy" }
        let p2 = {name:"zhangsan"}
        p2 = { ...age1, ...name1 } 
        // Amy overwrites Zhang San, indicating that the last generated value overwrites the original p2 value
        console.log(p2) // {age: 15, name: "Amy"}
    </script>
</body>

</html>

1.5 use of map and reduce

map(): receive a function to process all elements in the original array with this function and put them into the new array for return.
reduce() executes the callback function for each element in the array in turn, excluding the elements deleted or never assigned in the array

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
    <script>
        //map and reduce methods are added to the array.
         let arr = ['1', '20', '-5', '3'];
         
        //map(): receive a function to process all elements in the original array with this function and put them into the new array for return.
        //  arr = arr.map((item)=>{
        //     return item*2
        //  });
         arr = arr.map(item=> item*2);

        

         console.log(arr);
        //reduce() executes the callback function for each element in the array in turn, excluding the elements deleted or never assigned in the array,
        //[2, 40, -10, 6]
        //arr.reduce(callback,[initialValue])
        /**
        1,previousValue (The value returned by the last call callback, or the provided initial value (initialValue))
        2,currentValue (Elements currently being processed in the array)
        3,index (Index of the current element in the array)
        4,array ((array calling reduce)*/
        let result = arr.reduce((a,b)=>{
            console.log("After last treatment:"+a);
            console.log("Currently processing:"+b);
            return a + b;
        },100);
        console.log(result)

    
    </script>
</body>
</html>

1.6 optimizing asynchronous operation

Optimize asynchronous operations. Encapsulating ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <script>
        //1. Find out the current user information
        //2. Find out his course according to the current user's id
        //3. Find the score according to the current course id
        // $.ajax({
        //     url: "mock/user.json",
        //     success(data) {
        //         console.log("query user:", data);
        //         $.ajax({
        //             url: `mock/user_corse_${data.id}.json`,
        //             success(data) {
        //                 console.log("query course:", data);
        //                 $.ajax({
        //                     url: `mock/corse_score_${data.id}.json`,
        //                     success(data) {
        //                         console.log("query score:", data);
        //                     },
        //                     error(error) {
        //                         console.log("exception occurred:" + error);
        //                     }
        //                 });
        //             },
        //             error(error) {
        //                 console.log("exception occurred:" + error);
        //             }
        //         });
        //     },
        //     error(error) {
        //         console.log("exception occurred:" + error);
        //     }
        // });


        //1. Promise encapsulates asynchronous operations
        // Let P = new promise ((resolve, reject) = > {/ / the incoming message is successfully resolved, but rejected
        //     //1. Asynchronous operation
        //     $.ajax({
        //         url: "mock/user.json",
        //         success: function (data) {
        //             console.log("query user succeeded:", data)
        //             resolve(data);
        //         },
        //         error: function (err) {
        //             reject(err);
        //         }
        //     });
        // });

        // p. Then ((obj) = > {/ / what to do after success
        //     return new Promise((resolve, reject) => {
        //         $.ajax({
        //             url: `mock/user_corse_${obj.id}.json`,
        //             success: function (data) {
        //                 console.log("query user course succeeded:", data)
        //                 resolve(data);
        //             },
        //             error: function (err) {
        //                 reject(err)
        //             }
        //         });
        //     })
        // }). Then ((data) = > {/ / what will you do after success
        //     console.log("result of the previous step", data)
        //     $.ajax({
        //         url: `mock/corse_score_${data.id}.json`,
        //         success: function (data) {
        //             console.log("query course score succeeded:", data)
        //         },
        //         error: function (err) {
        //         }
        //     });
        // })

        function get(url, data) { //Define a method and integrate it
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: url,
                    data: data,
                    success: function (data) {
                        resolve(data);
                    },
                    error: function (err) {
                        reject(err)
                    }
                })
            });
        }

        get("mock/user.json")
            .then((data) => {
                console.log("User query succeeded~~~:", data)
                return get(`mock/user_corse_${data.id}.json`);
            })
            .then((data) => {
                console.log("Course query succeeded~~~:", data)
                return get(`mock/corse_score_${data.id}.json`);
            })
            .then((data)=>{
                console.log("Course score query succeeded~~~:", data)
            })
            .catch((err)=>{ //If it fails, catch
                console.log("An exception occurred",err)
            });

    </script>
</body>

</html>

corse_score_10.json score

{
    "id": 100,
    "score": 90
}

user.json user

{
    "id": 1,
    "name": "zhangsan",
    "password": "123456"
}

user_corse_1.json course

{
    "id": 10,
    "name": "chinese"
}

1.7 modularization

Modularization is to split the code to facilitate reuse. It is similar to the guided package in java, and JS is a guided module.

The module function mainly consists of two commands: export and import

export It is used to specify the external interface of the module
import Used to import functions provided by other modules

user.js

var name = "jack"
var age = 21
function add(a,b){
    return a + b;
}
// Export variables and functions
export {name,age,add}

hello.js

// export const util = {
//     sum(a, b) {
//         return a + b;
//     }
// }

// You can rename after export
export default {
    sum(a, b) {
        return a + b;
    }
}
// export {util}

//`Export ` you can export not only objects, but also all JS variables. For example, basic type variables, functions, arrays, and objects.

main.js

import abc from "./hello.js"
import {name,add} from "./user.js"

abc.sum(1,2);
console.log(name);
add(1,3);

2,VUE

2.1 introduction

Official website: https://cn.vuejs.org/v2/guide/
MVVM thought
M: model includes data and some basic operations
5: V iew view, page rendering results
VM: view model, two-way operation between model and view (without developer intervention)
The view and data are bound through the VM. Changes in the model will be automatically filled in the view through the Directives, and the added content in the view form will also be automatically saved to the model through DOM Listeners.

2.2 installation

Step 1: use npm Initialize project
npm init -y
 Step 2: installation vue Dependence of
npm install vue

2.3 vue syntax prompt and browser plug-in installation

Install plug-ins in vscode: Vetur and Vue 2 Snippets
Install plug-in in browser: Vue devtools

2.4 common grammar

Interpolation flashing:

use{{}}This method will have problems when the network speed is slow. When the data is not loaded, the page will display the original{{}},
The correct data is displayed only after loading, which is called interpolation flicker.
Let's slow down the network speed, then refresh the page and try the case just now

1,v-text,v-html.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
   
    <div id="app">
        {{msg}}  {{1+1}}  {{hello()}}<br/>
        <span v-html="msg"></span>
        <br/>
        <span v-text="msg"></span>

        
    </div>
   
    <script src="../node_modules/vue/dist/vue.js"></script>

    <script>
        new Vue({
            el:"#app",
            data:{
                msg:"<h1>Hello</h1>",
                link:"http://www.baidu.com"
            },
            methods:{
                hello(){
                    return "World"
                }
            }
        })
    </script>
    
</body>
</html>

2,v-bind.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <!-- to html Attribute binding for tags -->
    <div id="app"> 

        <a v-bind:href="link">gogogo</a>

        <!-- class,style  {class Name: plus?}-->
        <span v-bind:class="{active:isActive,'text-danger':hasError}"
          :style="{color: color1,fontSize: size}">Hello</span>


    </div>

    <script src="../node_modules/vue/dist/vue.js"></script>

    <script>
        let vm = new Vue({
            el:"#app",
            data:{
                link: "http://www.baidu.com",
                isActive:true,
                hasError:true,
                color1:'red',
                size:'36px'
            }
        })
    </script>

</body>
</html>

3 v-modal
Bidirectional binding

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>


    <!-- Form items, custom components -->
    <div id="app">

        Proficient language:
            <input type="checkbox" v-model="language" value="Java"> java<br/>
            <input type="checkbox" v-model="language" value="PHP"> PHP<br/>
            <input type="checkbox" v-model="language" value="Python"> Python<br/>
        Checked {{language.join(",")}}
    </div>
    
    <script src="../node_modules/vue/dist/vue.js"></script>

    <script>
        let vm = new Vue({
            el:"#app",
            data:{
                language: []
            }
        })
    </script>

</body>
</html>

4.v-on and @ onclick

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
                
        <!--Write directly in event js fragment-->
        <button v-on:click="num++">give the thumbs-up</button>
        <!--Event specifies a callback function, which must be Vue Functions defined in the instance-->
        <button @click="cancle">cancel</button>
        <!--  -->
        <h1>have{{num}}A praise</h1>


        <!-- Event modifier -->
        <div style="border: 1px solid red;padding: 20px;" v-on:click.once="hello">
            large div
            <div style="border: 1px solid blue;padding: 20px;" @click.stop="hello">
                Small div <br />
                <a href="http://www.baidu. Com "@click.prevent.stop =" hello "> go to Baidu</a>
            </div>
        </div>



        <!-- Key modifier: -->
        <input type="text" v-model="num" v-on:keyup.up="num+=2" @keyup.down="num-=2" @click.ctrl="num=10"><br />

        Tips:

    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>

    <script>
        new Vue({
            el:"#app",
            data:{
                num: 1
            },
            methods:{
                cancle(){
                    this.num--;
                },
                hello(){
                    alert("Click")
                }
            }
        })
    </script>
</body>

</html>
  1. v-for
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <div id="app">
        <ul>
            <!-- To improve rendering efficiency, add key field -->
            <li v-for="(user,index) in users" :key="user.name" v-if="user.gender == 'female'">
                <!-- 1,display user Information: v-for="item in items" -->
               Current index:{{index}} ==> {{user.name}}  ==>   {{user.gender}} ==>{{user.age}} <br>
                <!-- 2,Get array subscript: v-for="(item,index) in items" -->
                <!-- 3,Traversal object:
                        v-for="value in object"
                        v-for="(value,key) in object"
                        v-for="(value,key,index) in object" 
                -->
                Object information:
                <span v-for="(v,k,i) in user">{{k}}=={{v}}=={{i}};</span>
                <!-- 4,Add it when traversing:key To distinguish different data and improve vue Rendering efficiency -->
            </li>

            
        </ul>

        <ul>
            <li v-for="(num,index) in nums" :key="index"></li>
        </ul>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>
    <script>         
        let app = new Vue({
            el: "#app",
            data: {
                users: [{ name: 'Liuyan', gender: 'female', age: 21 },
                { name: 'Zhang San', gender: 'male', age: 18 },
                { name: 'Fan Bingbing', gender: 'female', age: 24 },
                { name: 'Liu Yifei', gender: 'female', age: 18 },
                { name: 'Gulinaza', gender: 'female', age: 25 }],
                nums: [1,2,3,4,4]
            },
        })
    </script>
</body>

</html>
  1. v-if and v-show
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <!-- 
        v-if,As the name suggests, conditional judgment. When the result is true The element is rendered only when.
        v-show,When the result is true The element is displayed only when. 
    -->
    <div id="app">
        <button v-on:click="show = !show">Order me</button>
        <!-- 1,use v-if display -->
        <h1 v-if="show">if=See me....</h1>
        <!-- 2,use v-show display -->
        <h1 v-show="show">show=See me</h1>
    </div>

    <script src="../node_modules/vue/dist/vue.js"></script>
        
    <script>
        let app = new Vue({
            el: "#app",
            data: {
                show: true
            }
        })
    </script>

</body>

</html>
  1. v-else and v-slse-if
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <button v-on:click="random=Math.random()">Order me</button>
        <span>{{random}}</span>

        <h1 v-if="random>=0.75">
            See me?! &gt;= 0.75
        </h1>

        <h1 v-else-if="random>=0.5">
            See me?! &gt;= 0.5
        </h1>

        <h1 v-else-if="random>=0.2">
            See me?! &gt;= 0.2
        </h1>

        <h1 v-else>
            See me?! &lt; 0.2
        </h1>

    </div>


    <script src="../node_modules/vue/dist/vue.js"></script>
        
    <script>         
        let app = new Vue({
            el: "#app",
            data: { random: 1 }
        })     
    </script>
</body>

</html>

2.5 calculation properties and listeners

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <!-- Some results are calculated in real time based on the previous data, and we can use the calculation attributes. To complete -->
        <ul>
            <li>Journey to the West; Price:{{xyjPrice}},number:<input type="number" v-model="xyjNum"> </li>
            <li>Water Margin; Price:{{shzPrice}},number:<input type="number" v-model="shzNum"> </li>
            <li>Total price:{{totalPrice}}</li>
            {{msg}}
        </ul>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>

    <script>
        //watch allows us to monitor the change of a value. So as to respond accordingly.
        new Vue({
            el: "#app",
            data: {
                xyjPrice: 99.98,
                shzPrice: 98.00,
                xyjNum: 1,
                shzNum: 1,
                msg: ""
            },
            // Calculate attribute, this xyjPrice*this. xyjNum + this. shzPrice*this. If the value in shznum changes, the totalPrice method will be triggered
            computed: {
                totalPrice(){
                    return this.xyjPrice*this.xyjNum + this.shzPrice*this.shzNum
                }
            },
            // The monitor here monitors the xyjNum attribute in data. It writes a method with the same name, two parameters, a new value and an old value
            watch: {
                xyjNum(newVal,oldVal){
                    if(newVal>=3){
                        this.msg = "Inventory exceeds limit";
                        this.xyjNum = 3
                    }else{
                        this.msg = "";
                    }
                }
            },
        })
    </script>

</body>

</html>

filter

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <!-- Filters are often used to handle text formatting. Filters can be used in two places: Double curly braces and interpolation v-bind expression -->
    <div id="app">
        <ul>
            <li v-for="user in userList">
                {{user.id}} ==> {{user.name}} ==> {{user.gender == 1?"male":"female"}} ==>
                {{user.gender | genderFilter}} ==> {{user.gender | gFilter}}
            </li>
        </ul>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>

    <script>
        // Global filter
        Vue.filter("gFilter", function (val) {
            if (val == 1) {
                return "male~~~";
            } else {
                return "female~~~";
            }
        })

        let vm = new Vue({
            el: "#app",
            data: {
                userList: [
                    { id: 1, name: 'jacky', gender: 1 },
                    { id: 2, name: 'peter', gender: 0 }
                ]
            },
            // Local filter
            filters: {
                 filters Define a local filter, which can only be used in the current vue Used in instances
                genderFilter(val) {
                    if (val == 1) {
                        return "male";
                    } else {
                        return "female";
                    }
                }
            }
        })
    </script>
</body>

</html>

2.6 componentization

Componentization

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <div id="app">
        <button v-on:click="count++">I was clicked {{count}} second</button>

        <counter></counter>
        <counter></counter>
        <counter></counter>
        <counter></counter>
        <counter></counter>

        <button-counter></button-counter>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>


    <script>
        //1. Global declaration register a component
        Vue.component("counter", {
            template: `<button v-on:click="count++">I was clicked {{count}} second</button>`,
            data() {
                return {
                    count: 1
                }
            }
        });

        //2. Local declaration of a component
        const buttonCounter = {
            template: `<button v-on:click="count++">I was clicked {{count}} second~~~</button>`,
            data() {
                return {
                    count: 1
                }
            }
        };

        new Vue({
            el: "#app",
            data: {
                count: 1
            },
            // Local components can be used only after they are registered
            components: {
                'button-counter': buttonCounter
            }
        })
    </script>
</body>

</html>

2.6 life cycle

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <span id="num">{{num}}</span>
        <button @click="num++">fabulous!</button>
        <h2>{{name}},have{{num}}Personal praise</h2>
    </div>

    <script src="../node_modules/vue/dist/vue.js"></script>
    
    <script>
        let app = new Vue({
            el: "#app",
            data: {
                name: "Zhang San",
                num: 100
            },
            methods: {
                show() {
                    return this.name;
                },
                add() {
                    this.num++;
                }
            },
            beforeCreate() {
                console.log("=========beforeCreate=============");
                console.log("Data model not loaded:" + this.name, this.num);
                console.log("Method not loaded:" + this.show());
                console.log("html Template not loaded:" + document.getElementById("num"));
            },
            created: function () {
                console.log("=========created=============");
                console.log("Data model loaded:" + this.name, this.num);
                console.log("Method loaded:" + this.show());
                console.log("html Template loaded:" + document.getElementById("num"));
                console.log("html Template not rendered:" + document.getElementById("num").innerText);
            },
            beforeMount() {
                console.log("=========beforeMount=============");
                console.log("html Template not rendered:" + document.getElementById("num").innerText);
            },
            mounted() {
                console.log("=========mounted=============");
                console.log("html Template rendered:" + document.getElementById("num").innerText);
            },
            beforeUpdate() {
                console.log("=========beforeUpdate=============");
                console.log("Data model updated:" + this.num);
                console.log("html Template not updated:" + document.getElementById("num").innerText);
            },
            updated() {
                console.log("=========updated=============");
                console.log("Data model updated:" + this.num);
                console.log("html Template updated:" + document.getElementById("num").innerText);
            }
        });
    </script>
</body>

</html>

3, Modular development of vue

3.1 installation

Open cmd and enter the command

## Step 1: install webpack -g indicates global installation
npm install webpack -g
## Part II: installation vue scaffold
npm install -g @vue/cli-init 
## Step 3: start the vue project. The vue scaffold initializes a project called vue demo through the webpack template
vue init webpack vue-demo
## Step 4: start vue project
cd vue-demo
npm run dev
## After startup: Your application is running here: http://localhost:8080
## Step 5: ctrl+C stops the project and integrates elementui. I means install
npm i element-ui


3.2 structure

3.3 single document component

3.4 routing view

3.5 code snippets for quickly generating templates

Setup code generation snippet

// https://www.cnblogs.com/songjilong/p/12635448.html
{
    "Print to console": {
        "prefix": "vue",
        "body": [
            "<!-- $1 -->",
            "<template>",
            "<div class='$2'>$5</div>",
            "</template>",
            "",
            "<script>",
            "//Here you can import other files (such as components, tools js, third-party plug-ins js, json files, picture files, etc.) ",
            "//For example: import component name from 'component path'; ",
            "",
            "export default {",
            "//The import ed components need to be injected into the object before they can be used ",
            "components: {},",
            "data() {",
            "//Data is stored here ",
            "return {",
            "",
            "};",
            "},",
            "//The listening attribute is similar to the data concept ",
            "computed: {},",
            "//Monitor data changes in data ",
            "watch: {},",
            "//Method collection ",
            "methods: {",
            "",
            "},",
            "//Lifecycle - creation completed (you can access the current instance of this ",
            "created() {",
            "",
            "},",
            "//Lifecycle - Mount complete (DOM elements can be accessed) ",
            "mounted() {",
            "",
            "},",
            "beforeCreate() {}, //Lifecycle - before creation ",
            "beforeMount() {}, //Lifecycle - before mounting ",
            "beforeUpdate() {}, //Lifecycle - before update ",
            "updated() {}, //Lifecycle - after update ",
            "beforeDestroy() {}, //Life cycle - before destruction ",
            "destroyed() {}, //Life cycle - destruction complete ",
            "activated() {}, //If the page has a keep alive cache function, this function will trigger ",
            "}",
            "</script>",
            "<style scoped>",
            "//@import url($3);  Introduce public css class ",
            "$4",
            "</style>"
        ],
        "description": "generate vue Template"
    },
    "http-get request": {
	"prefix": "httpget",
	"body": [
		"this.\\$http({",
		"url: this.\\$http.adornUrl(''),",
		"method: 'get',",
		"params: this.\\$http.adornParams({})",
		"}).then(({ data }) => {",
		"})"
	],
	"description": "httpGET request"
    },
    "http-post request": {
	"prefix": "httppost",
	"body": [
		"this.\\$http({",
		"url: this.\\$http.adornUrl(''),",
		"method: 'post',",
		"data: this.\\$http.adornData(data, false)",
		"}).then(({ data }) => { });" 
	],
	"description": "httpPOST request"
    }
}

4, vue integration elementui

Official website: https://element.eleme.cn/#/zh-CN/component/installation

# Direct npm installation, implemented in the project
npm i element-ui -S

# Or introduce styles

Use: in main JS

import ElementUI  from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';

// Let vue use the ElementUI component
Vue.use(ElementUI);

5, Import and export of components

For an overall function module, we can define it as a component. For example, for the left navigation, we can define it as a component, so that it can be easily called in other places. How to import, export and use components.
Step 1: define the component and the three elements of the component
a) Page layout
b) , write logic, and import other components in the component
c) . writing style
Step 2: export components, which are used for other component calls and export operations, and export default in b of the three elements of the component
For example: export default

<script>
//Other files can be imported here (such as components, tools js, third-party plug-ins js, json files, picture files, etc.)
//For example: import component name from 'component path';

export default {
  //The components introduced by import need to be injected into the object before they can be used
  components: {},
  props: {},
  data() {},
  //Computing properties is similar to the data concept
  computed: {},
  //Monitor data changes in data
  watch: {},
  //Method set
  methods: {
  },
  //Lifecycle - creation complete (you can access the current instance of this)
  created() {},
  //Lifecycle - Mount complete (DOM elements can be accessed)
  mounted() {},
  beforeCreate() {}, //Lifecycle - before creating
  beforeMount() {}, //Lifecycle - before mounting
  beforeUpdate() {}, //Lifecycle - before updating
  updated() {}, //Lifecycle - after update
  beforeDestroy() {}, //Life cycle - before destruction
  destroyed() {}, //Life cycle - destruction complete
  activated() {} //If the page has a keep alive cache function, this function will be triggered
};
</script>

Step 3: import and use in other components or pages
stay

<script>
//Import the component Category and name it Category 
import Category from "../common/category";
export default {
  //The components imported by import need to be injected into the object before they can be used. The first Category is the name of the component used
  components: { Category}, Equivalent to{Category:Category}

Use in

<template>
  <el-row :gutter="20">
    <el-col :span="6">
      <category @tree-node-click="treenodeclick"></category>
    </el-col>

6, vue parent-child components transfer data

6.1 data transfer from child component to parent component

Scenario: the child component is a three-level classification on the left. The parent component imports a three-level classification on the left, and the list corresponding to the three-level classification on the right. After the child component clicks the three-level classification, the parent component needs to update the list on the right.
Step 1: the child component sends the event this. To the parent component$ Emit ("event name", carried data...) can carry any number of data

    nodeclick(data, node, component) {
      console.log("Subcomponents category The node is clicked", data, node, component);
      //Send events to the parent component;
      this.$emit("tree-node-click", data, node, component);
    }

Step 2: the parent component senses that the event sent by the child component is in the template and goes to its own event

 <category @tree-node-click="treenodeclick"></category>

Step 3: define the parent component's own event, which is equivalent to binding with the sensed event of the child component

//Perception tree node is clicked
    treenodeclick(data, node, component) {
      if (node.level == 3) {
        this.catId = data.catId;
        this.getDataList(); //Re query
      }
    }

/**

  • The parent and child components pass data, and the current component is the parent component
  • 1) . the child component transmits data to the parent component, and the event mechanism;
  • The child component sends an event to the parent component to carry the data.
  • // this.$emit("event name", data carried...)
    */

matters needing attention

v-bind:src abbreviation: src
{"bac": abc} abbreviation {abc}

Topics: Javascript Vue.js Visual Studio Code