Vue quick start (IDEA version) one article is a quick start (you can directly develop front-end and back-end separation projects)

1, Vue quick start

In 2008, google's Chrome was released, and then it occupied the market at a very fast speed, surpassing IE to become the leader of the browser market.

In 2009, based on Google's Chrome v8 engine, Ryan Dahl created an asynchronous IO framework based on event loop: node js.

Asynchronous lO based on time cycle

Single thread operation to avoid multi-threaded variable synchronization
JS can write background diamante, front and rear platform system ━ programming language
node. The greatness of JS is not to make JS move towards back-end development, but to build a huge ecosystem.

In 2010, NPM served as node JS package management system is released for the first time, and developers can follow common JS specification to write node JS module, and then publish it to NPM for other developers to use.
At present, it is the world's largest package module management system.

Subsequently, a large number of front-end frameworks emerged on the basis of node:

MVVM mode

M: That is, Model, including data and some basic operations

5: That is, View, page rendering results

VM: view model, two-way operation between model and view (without developer intervention)

Before MWM, developers obtain the required data Model from the back end, and then operate the Model through DOM to render it into View.

Then, when the user operates the View, we also need to obtain the data in the View through the DOM, and then synchronize it to the Model.

What the VM in MVVM needs to do is to completely encapsulate the DOM operation. Developers no longer need to care about how the Model and View affect each other:

● as long as our Model changes, it will naturally appear on the View.
● when the user modifies the View, the data in the Model will also change.

Liberate developers from cumbersome DOM operations and focus on how to operate the Model.

What we want to learn today is a framework of MVVM pattern: Vue

1. Meet Vue

WUE (pronounced / vju: /, similar to view) is a progressive framework for building user interfaces.
Unlike other large frameworks, Vue is designed to be applied layer by layer from bottom to top.
Vue's core library only focuses on view layers, which is not only easy to start, but also easy to integrate with third-party libraries or existing projects.
On the other hand, when combined with modern industrial photography and various support libraries, Vue can also provide drivers for complex single page applications

https://cn.vuejs.org/

2. Install node js

(1) Enter node JS official website https://nodejs.org/zh-cn/







Then install

installation is complete
Console test
Enter node-v and enter

2,NPM

npm version, enter npm -v and press enter

The default warehouse address of npm is on foreign websites, which is slow. It is recommended to set it to Taobao image.
However, image switching is troublesome. The recommended tool for image switching is nrm

We first install nrm, where - g stands for global installation

npm install nrm -g

Input: nrm ls error


Locate the file C:\Users\ZHENG\AppData\Roaming\npm\node_modules\nrm

//const NRMRC = path.join(process.env.HOME, '.nrmrc');  (deleted)
const NRMRC = path.join(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], '.nrmrc');

Continue entering nrm ls

Switch Taobao image nrm use taobao

Test nrm test taobao

2, Engineering case

1. Create project







2. Install Vue

In the terminal of IDEA

Enter: npm init -y on the terminal and an error is reported


(1) Initialize project
npm init -y

(2) Install Vue

Only install Vue for the current project: npm install vue --save

Open the following content to prove that the installation is complete

3. Create HTML file

(1) Write basic HTML pages



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <h1>
            xxx Very beautiful!
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
</script>
</body>
</html>

Run and check

(2) Using Vue

a. Define properties

First, create a Vue instance through new Vue()

Then the constructor receives an object with some properties:

  • el: is the abbreviation of element. Select the page element to be rendered by id. in this case, it is a div
  • Data: data. Data is an object with many attributes that can be rendered to the view
  • Name: Here we specify a name attribute

In the h2 element in the page, we render the name attribute just defined by {{name)}.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <h1>
           {{name}} xxx Very beautiful!
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"Tiger brother"
        }
    });
</script>
</body>
</html>

Run test


Google browser console


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <h1>
           {{name}} xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"Tiger brother",
            num: 1,
        }
    });
</script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <input type="text" v-model="num" />
        <h1>
           {{name}} xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"Tiger brother",
            num: 1,
        }
    });
</script>
</body>
</html>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <h1>
           {{name}} xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"Tiger brother",
            num: 1,
        }
    });
</script>
</body>
</html>


b. Define properties

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <h1>
           {{name}} xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"Tiger brother",
            num: 1,
        },
        methods : {
            handleClick(){
                console.log("hello");
            }
        }
    });
</script>
</body>
</html>


3, Vue lifecycle (hook)

Each Vue instance goes through a series of initialization processes when it is created:

Create instances, load templates, render templates, and so on. Vue sets a hook function (listener function) for each state in the lifecycle.

Each time a Vue instance is in a different lifecycle, the corresponding function is triggered.

1. Life cycle:

2. Render data: hook functions

For example: created means after the vue instance is created;
We can define a created function in Vue to represent the constructor of this period;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <h1>
           {{name}} xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "Tiger brother";
        }
    });
</script>
</body>
</html>




3. Simulate the actual rendering data: this, we can see who the this variable inside vue is. When we create, we print this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <h1>
           {{name}} xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            setTimeout(() => this.name = "Tiger, really",1000)
        }
    });
</script>
</body>
</html>


One second delay

Summary: This is the current Vue instance. Within the Vue object, you must use this to access the data attributes and methods defined in Vue.

4, Instruction

What are instructions?
Directives are special attributes with a v-prefix.

For example, the v-model in our introductory case represents two-way binding.

1. Interpolation expression

(1) Curly bracket

Format:

{{expression}}

explain;

  • The expression supports JS syntax and can call JS built-in functions (there must be a return value)
  • The expression must have a return result. For example, 1 + 1, expressions without results are not allowed, such as var a = 1+1;
  • You can directly obtain the data or functions defined in the Vue instance

Example
HTML:

<div id= " app">i{name ) )</div>

JS:

var app =new vue({
	el:"#app",
	data:{
		name:"Jack""
	}
})

2. Difference flashing

Using 0 mode will cause 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 and try the case just now:


There is a delay in refreshing the page

3. Using v-text and v-html

Use the v-text and v-html instructions instead of {} instructions:

v-text: output data to the inside of the element, if the output data has
Code, which will be output as normal text

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <h1>
           <span v-text="name"></span> xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "Tiger, really",1000;
        }
    });
</script>
</body>
</html>

Run test

v-html: output the data to the inside of the element. If the output data has HTML code, it will be rendered



There seems to be no difference from the above results
Continue to modify the code below

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <h1>
           <span v-text="name"></span> xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
        <span v-text="name"></span><br>
        <span v-html="name"></span>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "<font color='#8a2be2 '> tiger < font > ";
        }
    });
</script>
</body>
</html>


v-text: output the data to the inside of the element. If the output data has HTML code, it will be output as normal text
v-html: output the data to the inside of the element. If the output data has HTML code, it will be rendered

4,v-model

v-text and v-html can be regarded as one-way binding. The data affects the view rendering, but not the other way around.

Next, the v-model learned is a two-way binding, and views and models will affect each other.

Since it is a two-way binding, you must be able to modify data in the view, which limits the element type of the view.

Currently, the available elements of v-model are:

  • input
  • select
  • textarea
  • checkbox
  • radio
  • Components (custom components in Vue)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <h1>
           <span v-text="name"></span> xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
        <span v-text="name"></span><br>
        <span v-html="name"></span>

        <hr/>
        <h1>Programming language classification</h1>
        <input type="checkbox" v-model="lessons" value="Java" />Java <br/>
        <input type="checkbox" v-model="lessons" value="JavaScript" />JavaScript <br/>
        <input type="checkbox" v-model="lessons" value="Python" />Python <br/>
        <h1>
            You have purchased the following courses:{{lessons.join(",")}}
        </h1>

    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
            lessons: []
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "<font color='#8a2be2 '> tiger < font > ";
        }
    });
</script>
</body>
</html>

Run view

5,v-on

(1) Basic usage

The v-on instruction is used to bind events to page elements.

Syntax:

v-on:Event name="js Fragment or function name"

Abbreviation syntax:
really

@Event name="js Fragment or function name“

For example, v-on:click='add 'can be abbreviated as @ click='add'

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <button @click="decrement">-</button>
        <h1>
           <span v-text="name"></span> xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
        <span v-text="name"></span><br>
        <span v-html="name"></span>

        <hr/>
        <h1>Programming language classification</h1>
        <input type="checkbox" v-model="lessons" value="Java" />Java <br/>
        <input type="checkbox" v-model="lessons" value="JavaScript" />JavaScript <br/>
        <input type="checkbox" v-model="lessons" value="Python" />Python <br/>
        <h1>
            You have purchased the following courses:{{lessons.join(",")}}
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
            lessons: []
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            },
            decrement(){
                this.num--;
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "<font color='#8a2be2 '> tiger < font > ";
        }
    });
</script>
</body>
</html>


(2) Click event (including relationship (bubble))

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <button @click="decrement">-</button>
        <h1>
           <span v-text="name"></span> xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
        <span v-text="name"></span><br>
        <span v-html="name"></span>

        <hr/>
        <h1>Programming language classification</h1>
        <input type="checkbox" v-model="lessons" value="Java" />Java <br/>
        <input type="checkbox" v-model="lessons" value="JavaScript" />JavaScript <br/>
        <input type="checkbox" v-model="lessons" value="Python" />Python <br/>
        <h1>
            You have purchased the following courses:{{lessons.join(",")}}
        </h1>

        <hr/>
        <!--v-on-->
        <div style="width: 100px; height: 100px; background-color:indianred; " @click="print('div')">
            div
            <button @click="print('button')">Let me try</button>
        </div>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
            lessons: []
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            },
            decrement(){
                this.num--;
            },print(msg){
                console.log(msg)
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "<font color='#8a2be2 '> tiger < font > ";
        }
    });
</script>
</body>
</html>

Click inside to trigger two at the same time

Click outside to trigger an event

(3) Click event (set not to automatically include relationship (stop bubbling))

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <button @click="decrement">-</button>
        <h1>
           <span v-text="name"></span> xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
        <span v-text="name"></span><br>
        <span v-html="name"></span>

        <hr/>
        <h1>Programming language classification</h1>
        <input type="checkbox" v-model="lessons" value="Java" />Java <br/>
        <input type="checkbox" v-model="lessons" value="JavaScript" />JavaScript <br/>
        <input type="checkbox" v-model="lessons" value="Python" />Python <br/>
        <h1>
            You have purchased the following courses:{{lessons.join(",")}}
        </h1>

        <hr/>
        <!--v-on-->
        <div style="width: 100px; height: 100px; background-color:indianred; " @click.stop="print('div')">
            div
            <button @click.stop="print('button')">Let me try</button>
        </div>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
            lessons: []
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            },
            decrement(){
                this.num--;
            },print(msg){
                console.log(msg)
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "<font color='#8a2be2 '> tiger < font > ";
        }
    });
</script>
</body>
</html>



In this case, you only need to add one

(4) Event modifier

Calling event. in event handler Preventdefault() or event Stoppropagation () is a very common requirement.

Although we can easily implement this in methods, it is better that methods only have pure data logic, rather than dealing with DOM event details.

To solve this problem, Vue JS provides event modifiers for v-on.

As mentioned earlier, modifiers are represented by the instruction suffix beginning with a dot

  • Stop: stop event bubbling
  • prevent: prevents default events from occurring
  • Capture: use event capture mode
  • self: only the event triggered by the element itself can be executed. (neither bubbling nor trapping is performed)
  • Once: execute only once
(5) Prevent default events from happening

Block a label jump

<a href="http://www.baidu. Com "@ click. Prevent =" print ('baidu ') "> Baidu once, you're crazy</a>

7,v-for

Traversing the data rendering page is a very common requirement, which is implemented through the v-for instruction in Vue.

(1) Traversal array

Syntax:

v-for="item in items ""
  • items: the array to be traversed needs to be defined in vue's data.
  • item: alias of array element obtained by iteration
    Example:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <button @click="decrement">-</button>
        <h1>
           <span v-text="name"></span> xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
        <span v-text="name"></span><br>
        <span v-html="name"></span>

        <hr/>
        <h1>Programming language classification</h1>
        <input type="checkbox" v-model="lessons" value="Java" />Java <br/>
        <input type="checkbox" v-model="lessons" value="JavaScript" />JavaScript <br/>
        <input type="checkbox" v-model="lessons" value="Python" />Python <br/>
        <h1>
            You have purchased the following courses:{{lessons.join(",")}}
        </h1>

        <hr/>
        <!--v-on-->
        <div style="width: 100px; height: 100px; background-color:indianred; " @click="print('div')">
            div
            <button @click.stop="print('button')">Let me try</button>

        </div>
        <a href="http://www.baidu. Com "@ click. Prevent =" print ('baidu ') "> Baidu once, you're crazy</a>

        <hr>
        <!--v-for-->
        <ul>
            <li v-for="u in users">
                {{u.name + "," + u.gender + ","+ u.age }}
            </li>
        </ul>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
            lessons: [],
            users:[
                {name:'Liuyan',gender:'female',age:21},
                {name:'Tiger brother',gender:'male',age:30},
                {name:'Fan Bingbing',gender:'female',age:24},
                {name:'Liu Yifei',gender:'female',age:18},
                {name:'Gulinaza',gender:'female',age:25}
            ]
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            },
            decrement(){
                this.num--;
            },print(msg){
                console.log(msg)
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "<font color='#8a2be2 '> tiger < font > ";
        }
    });
</script>
</body>
</html>

Operation results

(2) Traversal array: multiple parameters (array subscript)

In the process of traversal, if we need to know the array subscript, we can specify the second parameter:
grammar

v-for=" (item, index) in items "
  • items: array to iterate
  • item: array element alias obtained by iteration
  • Index: the index of the current element iterated to, starting from 0.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <button @click="decrement">-</button>
        <h1>
           <span v-text="name"></span> xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
        <span v-text="name"></span><br>
        <span v-html="name"></span>

        <hr/>
        <h1>Programming language classification</h1>
        <input type="checkbox" v-model="lessons" value="Java" />Java <br/>
        <input type="checkbox" v-model="lessons" value="JavaScript" />JavaScript <br/>
        <input type="checkbox" v-model="lessons" value="Python" />Python <br/>
        <h1>
            You have purchased the following courses:{{lessons.join(",")}}
        </h1>

        <hr/>
        <!--v-on-->
        <div style="width: 100px; height: 100px; background-color:indianred; " @click="print('div')">
            div
            <button @click.stop="print('button')">Let me try</button>

        </div>
        <a href="http://www.baidu. Com "@ click. Prevent =" print ('baidu ') "> Baidu once, you're crazy</a>

        <hr>
        <!--v-for-->
        <ul>
            <li v-for="(u,i) in users">
              {{i}}  {{u.name + "," + u.gender + ","+ u.age }}
            </li>
        </ul>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
            lessons: [],
            users:[
                {name:'Liuyan',gender:'female',age:21},
                {name:'Tiger brother',gender:'male',age:30},
                {name:'Fan Bingbing',gender:'female',age:24},
                {name:'Liu Yifei',gender:'female',age:18},
                {name:'Gulinaza',gender:'female',age:25}
            ]
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            },
            decrement(){
                this.num--;
            },print(msg){
                console.log(msg)
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "<font color='#8a2be2 '> tiger < font > ";
        }
    });
</script>
</body>
</html>

(3) Traversal object

        <ul>
            <li v-for="u in users[0]">
                {{u}}
            </li>
        </ul>

(4) Traversal object: multiple parameters

        <ul>
            <li v-for="(u,i) in users[0]">
                {{u + "," + i }}
            </li>
        </ul>


     <ul>
            <li v-for="(v,k,i) in users[0]">
                {{i +"_"+ v + "," + k }}
            </li>
        </ul>

(5) Traversal number

		 <ul>
            <li v-for="i in 5">
                {{i}}
            </li>
        </ul>

8,key

When Vue When JS is updating the list of rendered elements with v-for, it uses the "reuse in place" policy by default.

If the order of data items is changed, Vue will not move DOM elements to match the order of data items, but simply reuse each element here and ensure that it displays each element that has been rendered under a specific index.

This function can effectively improve the efficiency of rendering.

However, to implement this function, you need to give Vue some tips so that it can track the identity of each node, so as to reuse and reorder existing elements
you

You need to provide a unique key attribute for each item. The ideal key value is a unique id that each item has.

Speed up data loading

		 <!--v-for-->
        <ul>
            <li v-for="(u,i) in users" :key="u.name">
              {{i}}  {{u.name + "," + u.gender + ","+ u.age }}
            </li>
        </ul>


Bind the angle of the array

		 <!--v-for-->
        <ul>
            <li v-for="(u,i) in users" :key="i">
              {{i}}  {{u.name + "," + u.gender + ","+ u.age }}
            </li>
        </ul>

9. v-if and v-show

v-if, as the name suggests, conditional judgment. When the result is true, the element will be rendered.
Syntax:

v-if"Boolean expression

example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button @click="handleClick">Point me</button><br>
        <input type="text" v-model="num" /><button @click="num++">+</button>
        <button @click="decrement">-</button>
        <h1>
           <span v-text="name"></span> xxx Very beautiful!<br>
            {{num}} It's fascinating!
        </h1>
        <span v-text="name"></span><br>
        <span v-html="name"></span>

        <hr/>
        <h1>Programming language classification</h1>
        <input type="checkbox" v-model="lessons" value="Java" />Java <br/>
        <input type="checkbox" v-model="lessons" value="JavaScript" />JavaScript <br/>
        <input type="checkbox" v-model="lessons" value="Python" />Python <br/>
        <h1>
            You have purchased the following courses:{{lessons.join(",")}}
        </h1>

        <hr/>
        <!--v-on-->
        <div style="width: 100px; height: 100px; background-color:indianred; " @click="print('div')">
            div
            <button @click.stop="print('button')">Let me try</button>

        </div>
        <a href="http://www.baidu. Com "@ click. Prevent =" print ('baidu ') "> Baidu once, you're crazy</a>

        <hr>
        <!--v-for-->
        <ul>
            <li v-for="(u,i) in users" :key="i">
              {{i}}  {{u.name + "," + u.gender + ","+ u.age }}
            </li>
        </ul>

        <ul>
            <li v-for="(v,k,i) in users[0]">
                {{i +"_"+ v + "," + k }}
            </li>
        </ul>
        <ul>
            <li v-for="i in 5">
                {{i}}
            </li>
        </ul>
        <hr/>
        <!--v-if-->
        <button @click="show != show">Click switch</button><br>
        <h1 v-if="show">
            Hello
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            name:"",
            num: 1,
            lessons: [],
            users:[
                {name:'Liuyan',gender:'female',age:21},
                {name:'Tiger brother',gender:'male',age:30},
                {name:'Fan Bingbing',gender:'female',age:24},
                {name:'Liu Yifei',gender:'female',age:18},
                {name:'Gulinaza',gender:'female',age:25}
            ],
            show: true,
        },
        methods : {
            handleClick(){
                console.log(this)
                console.log("hello");
            },
            decrement(){
                this.num--;
            },print(msg){
                console.log(msg)
            }
        },
        created(){
            //Initiate an Ajax request to the background to complete the initialization of data
            this.name = "<font color='#8a2be2 '> tiger < font > ";
        }
    });
</script>
</body>
</html>

On page

After clicking, you will disappear (after clicking, the trigger event will change show to false)

10. v-if combined with v-for and v-else

(1)v-if

When v-if and v-for appear together, v-for takes precedence.

In other words, it will traverse first and then judge the conditions.

Example:

  <ul>
        <li v-for="i in 5" v-if="i%2 === 0"  >
             {{i}}
        </li>
  </ul>

(2)v-else

 		<ul>
            <li v-for="i in 5">
                <span v-if="i%2 === 0">even numbers: {{i}} </span>
                <span v-else style="background-color:#cccccc; "> odd: {{I}} < / span > < br >
            </li>
        </ul>

11,v-show

Compare v-if and v-show

		 <h1 v-if="show">
            Hello
        </h1>
        <h1 v-show="show">
            You're fine, I remember!
        </h1>

Operation effect

disappear

The above looks no different from the outside

But when we opened it, we found

Before clicking


After clicking, it is found that v-if directly deletes the node, while v-show sets the style attribute display:none to hide the attribute

12,v-bind

(1) Create a new HTML page

<!DOCTYPE html>
<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>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{

        }
    });
</script>
</body>
</html>
(2) Writing CSS styles and HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        div #box{
            width:100px;
            height: 100px;
            color: darkgray;
        }
        .red{
            background-color: red;
        }
        .blue{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="app">
        <button>gules</button>
        <button>blue</button>
        <div id="box" class="red">
            I'm a box
            I'm a box
        </div>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{

        }
    });
</script>
</body>
</html>
(3) Add the event of clicking to switch pictures

a. According to the above normal solution thinking, it is solved by difference expression

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        div #box{
            width:100px;
            height: 100px;
            color: darkgray;
        }
        .red{
            background-color: red;
        }
        .blue{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="app">
        <button @click="color='red'">gules</button>
        <button @click="color='blue'">blue</button>
        <div id="box" class="{{color}}">
            I'm a box
            I'm a box
        </div>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            color:"red",
        }
    });
</script>
</body>
</html>

But in fact, the above practice is wrong

Difference expression cannot be used in attributes

b. The above solution is wrong. The following code uses v-bind
Modify the above code




c. Continue to update the special usage of the v-bind:class attribute in the above code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        div #box{
            width:100px;
            height: 100px;
            color: darkgray;
        }
        .red{
            background-color: red;
        }
        .blue{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="app">
        <button @click="isRed=!isRed">Click me to switch colors</button>
        <div id="box" :class="{red:isRed, blue:!isRed}" >
            I'm a box
            I'm a box
        </div>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            isRed:true
        }
    });
</script>
</body>
</html>



13. Calculation properties

It is very convenient to use js expression in interpolation expression, and it is often used.

However, if the content of the expression is very long, it will not be elegant enough, and it is inconvenient to maintain in the later stage

For example, in the following scenario, we have data of a date, but it is a millisecond value:

(a) Formatting of dates

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        div #box{
            width:100px;
            height: 100px;
            color: darkgray;
        }
        .red{
            background-color: red;
        }
        .blue{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="app">
        <!--class attribute-->
        <button @click="isRed=!isRed">Click me to switch colors</button>
        <div id="box" :class="{red:isRed, blue:!isRed}" >
            I'm a box
            I'm a box
        </div>
        <!--Calculation properties-->
        <h1>
            Your birthday:{{ birth }}
        </h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            isRed:true,
            birthday : 1529032123201 //Millisecond value
        },
        computed:{
            birth(){
                const day = new Date(this.birthday);
                return day.getFullYear() + "year" + day.getMinutes() +"month" + day.getDay() + "day";
            }
        }
    });
</script>
</body>
</html>

14,watch

(1) Monitor

watch allows us to monitor the change of a value and respond accordingly.

Automatic monitoring
Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        div #box{
            width:100px;
            height: 100px;
            color: darkgray;
        }
        .red{
            background-color: red;
        }
        .blue{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="app">
        <!--class attribute-->
        <button @click="isRed=!isRed">Click me to switch colors</button>
        <div id="box" :class="{red:isRed, blue:!isRed}" >
            I'm a box
            I'm a box
        </div>
        <!--Calculation properties-->
        <h1>
            Your birthday:{{ birth }}
        </h1>
        <!--watch-->
        <input type="text" v-model="num" />
        <h1>num:{{ num }}</h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            isRed:true,
            birthday : 1529032123201, //Millisecond value
            num : 1,
        },
        computed:{
            birth(){
                const day = new Date(this.birthday);
                return day.getFullYear() + "year" + day.getMinutes() +"month" + day.getDay() + "day";
            }
        }
    });
</script>
</body>
</html>

(2) Shallow monitoring

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        div #box{
            width:100px;
            height: 100px;
            color: darkgray;
        }
        .red{
            background-color: red;
        }
        .blue{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="app">
        <!--class attribute-->
        <button @click="isRed=!isRed">Click me to switch colors</button>
        <div id="box" :class="{red:isRed, blue:!isRed}" >
            I'm a box
            I'm a box
        </div>
        <!--Calculation properties-->
        <h1>
            Your birthday:{{ birth }}
        </h1>
        <!--watch-->
        <input type="text" v-model="num" />
        <h1>num:{{ num }}</h1>
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            isRed:true,
            birthday : 1529032123201, //Millisecond value
            num : 1,
        },
        computed:{
            birth(){
                const day = new Date(this.birthday);
                return day.getFullYear() + "year" + day.getMinutes() +"month" + day.getDay() + "day";
            }
        },
        watch:{
            num(newVal,oldVal){
                console.log(newVal,oldVal);
            }
        }
    });
</script>
</body>
</html>

function

newVal is the latest value and oldVal is the old value

(3) Deep monitoring


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        div #box{
            width:100px;
            height: 100px;
            color: darkgray;
        }
        .red{
            background-color: red;
        }
        .blue{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="app">
        <!--class attribute-->
        <button @click="isRed=!isRed">Click me to switch colors</button>
        <div id="box" :class="{red:isRed, blue:!isRed}" >
            I'm a box
            I'm a box
        </div>
        <!--Calculation properties-->
        <h1>
            Your birthday:{{ birth }}
        </h1>
        <!--watch-->
        <input type="text" v-model="num" />
        <h1>num:{{ num }}</h1>
        <input type="text" v-model="person.age" />
    </div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const app = new Vue({
        el:"#app",//elemnet,vue function label
        data:{
            isRed:true,
            birthday : 1529032123201, //Millisecond value
            num : 1,
            person:{
                name:"Jack",
                age : 21
            }
        },
        computed:{
            birth(){
                const day = new Date(this.birthday);
                return day.getFullYear() + "year" + day.getMinutes() +"month" + day.getDay() + "day";
            }
        },
        watch:{
            num(newVal,oldVal){
                console.log(newVal,oldVal);
            },
            person:{
                deep:true,
                handler(val){
                    console.log(val.age)
                }
            }
        }
    });
</script>
</body>
</html>

5, Componentization

In large-scale application development, the page can be divided into many parts.

Often different pages have the same parts. For example, there may be the same head navigation.

However, if each page is monologue developed, it will increase the cost of our development.

Therefore, we will split different parts of the page into independent components, and then share these components on different pages to avoid repeated development.

1. Define security components

We define a global component through Vue's component method.
Create a new page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <counter></counter>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    //Define global components with two parameters: 1 Component name 2 Component parameters
    Vue.component("counter",{
        template:"<button @click='count++'>Let me try{{ count }}I remember you!</button>",
        data(){
            return{
                count :0
            }
        }
    }) ;
    var app = new Vue({
        el:"#app"
    })
</script>
</body>
</html>

2. Reuse of components

The defined components can be reused multiple times at will:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <!--Use defined global components-->
    <counter></counter>
    <counter></counter>
    <counter></counter>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    //Define global components with two parameters: 1 Component name 2 Component parameters
    Vue.component("counter",{
        template:"<button @click='count++'>Let me try{{ count }}I remember you!</button>",
        data(){
            return{
                count :0
            }
        }
    }) ;
    var app = new Vue({
        el:"#app"
    })
</script>
</body>
</html>


The data attribute of the component must be a function!
When we define this < counter > component, its data does not directly provide an object like this:

data: {
  count: 0
}

Instead, the data option of a component must be a function, so each instance can maintain an independent copy of the returned object:

data: function () {
  return {
    count: 0
  }
}

If Vue does not have this rule, clicking a button will affect all other instances!

3. Local registration

Once locally registered, it means that even if you no longer use this component in the future, it will still be loaded with the loading of Vue.

Therefore, for some components that are not used frequently, we will use local registration.

We first define an object externally, and the structure is consistent with the second parameter passed when creating the component:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <!--Use defined global components-->
    <counter></counter>
    <counter></counter>
    <counter></counter>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    //Define global components with two parameters: 1 Component name 2 Component parameters
    const counter = {
        template:'<button v-on:click="count++">You ordered me {{ count }} Once, I remember.</button>',
        data(){
            return {
                count:0
            }
        }
    };
    var app = new Vue({
        el:"#app",
        comments:{
            counter:counter //Register the defined object as a component
        }
    })
</script>
</body>
</html>
  • components is the collection of subcomponents of the current vue object.
    The key is the sub component name
    Its value is the attribute of the component object
  • The effect is similar to the global registration just now, except that this counter component can only be used in the current Vue instance

4. Component communication

Usually, a single page application is organized in the form of a nested component tree:

  • The page is first divided into top navigation and left content area,
  • The left content area is divided into upper and lower components
  • The right sidebar contains three sub components

Various components are combined in nested relationships, so there will inevitably be the need for communication between components at this time.

(1) Pass parent to child: props

For example, we have a sub component:

Vue.component("introduce",{
    // Render the page directly using the properties received by props
    template:'<h3>{{title}}</h3>',
    props:[title] // Receive the properties passed by a parent component through props
})
  • This subcomponent uses the title attribute to render the page, but it does not have the title attribute itself
  • Receive the parent component attribute through props, named title

The parent component uses the child component and passes the title attribute:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <h1>Say hello:</h1>
    <!--Use subcomponents while passing title attribute-->
    <introduce title="Hello, I'm brother Hu"/>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    //Define global components with two parameters: 1 Component name 2 Component parameters
    Vue.component("introduce",{
        //Directly use props to receive attributes to render the page
        template:'<h3>{{ title }}</h3>',
        props:['title'] //Receive a parent component to pass attributes through props
    })
    var app = new Vue({
        el:"#app"
    })
</script>
</body>
</html>

(2) Transfer complex data

We define a sub component:

const myList = {
    template:'\
        <ul>\
        	<li v-for="item in items" :key="item.id">{{item.id}} : {{item.name}}</li>\
        </ul>\
        ',
    props:{ // Receive the properties passed by the parent component through props
        items:{// The items attribute is defined here
            type:Array,// Array type is required
            default:[] // If the parent component is not passed, the given default value is []
        }
	}
}
  • This subcomponent can iterate over the items and output them to the page.
  • However, the items property is not defined in the component.
  • Define the properties to be received from the parent component through props
    • items: is the name of the attribute to receive
      • type: the passed from the parent component must be an array, otherwise an error will be reported
      • Default: the default value

We use it in the parent component:
All codes:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <h2>Course:</h2>
    <!-- While using sub components, you can pass attributes. Here you use v-bind,Points to the parent component's own properties lessons -->
    <my-list :items="lessons"/>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    const myList = {
        template: '\
            <ul>\
                <li  v-for="item in items" :key="item.id">{{item.id}} : {{item.name}}</li>\
            </ul>\
        ',
        props:{ // Receive the properties passed by the parent component through props
            items:{ // The items attribute is defined here
                type:Array, // Array type is required
                default:[] // If the parent component is not passed, the given default value is []
            }
        }
    }
    var app = new Vue({
        el:"#app",
        components:{
            myList//When key and value are the same, you can write only one
        },
        data:{
            lessons:[
                {id:1, name: 'java'},
                {id:2, name: 'php'},
                {id:3, name: 'ios'},
            ]
        }
    })

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


(3) Child to parent communication

Let's look at a case:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <h2>num: {{ num }}</h2>
    <!-- While using subcomponents, pass num Into sub components -->
    <counter :num="num"></counter>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    Vue.component("counter",{//The subcomponent defines two buttons. Clicking the number num will add or subtract
        template:'\
             <div>\
                 <button @click="num++">plus</button>\
                 <button @click="num--">reduce</button>\
             </div> ',
        props:['num']//count is obtained from the parent component.
    })
    var app = new Vue({
        el:"#app",
        data:{
            num:0
        }
    })

</script>
</body>
</html>
  • The child component receives the num attribute of the parent component
  • Click the sub component definition button to add or subtract num

We tried to run:

After the child component receives the parent component property, it is not allowed to modify by default. What should I do?

Since only the parent component can be modified, the addition and subtraction operations must be placed on the parent component

var app = new Vue({
    el:"#app",
    data:{
        num:0
    },
    methods:{ // The method of operating num is defined in the parent component
        increment(){
            this.num++;
        },
        decrement(){
            this.num--;
        }
    }
})


All codes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <h2>num: {{num}}</h2>
    <counter :count="num" @inc="increment" @dec="decrement"></counter>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    Vue.component("counter", {
        template:'\
                <div>\
                    <button @click="plus">plus</button>  \
                    <button @click="reduce">reduce</button>  \
                </div>',
        props:['count'],
        methods:{
            plus(){
                this.$emit("inc");
            },
            reduce(){
                this.$emit("dec");
            }
        }
    })
    var app = new Vue({
        el:"#app",
        data:{
            num:0
        },
        methods:{ // The method of operating num is defined in the parent component
            increment(){
                this.num++;
            },
            decrement(){
                this.num--;
            }
        }
    })

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

However, clicking the button is in the child component, that is, the child component needs to call the function of the parent component. What should I do?

We can bind the functions of the parent component to the child component through the v-on instruction:

<div id="app">
    <h2>num: {{num}}</h2>
    <counter :count="num" @inc="increment" @dec="decrement"></counter>
</div>

Then, when the button in the sub component is clicked, call the bound function:

 Vue.component("counter", {
            template:'\
                <div>\
                    <button @click="plus">plus</button>  \
                    <button @click="reduce">reduce</button>  \
                </div>',
            props:['count'],
            methods:{
                plus(){
                    this.$emit("inc");
                },
                reduce(){
                    this.$emit("dec");
                }
            }
        })

vue provides a built-in this$ The emit function is used to call the function bound by the parent component
effect:

Keywords: Javascript css3 html5 IntelliJ IDEA Vue

Added by Grant Holmes on Thu, 13 Jan 2022 21:53:40 +0200