https://cn.vuejs.org/
1, What is Vue
1. Introduction
Vue (pronounced / vju: /, similar to view) is a progressive js framework for building user interfaces, which was released in February 2014.
Unlike other large frameworks, Vue is designed to be applied layer by layer from bottom to top.
Vue's core library only focuses on visual layers, which is not only easy to start, but also easy to integrate with third-party libraries (such as Vue router, Vue resource, vuex) or existing projects.
Combined with HTML+CSS+JS, it has a good ecosystem, and vue is small, fast and optimized in place.
2. Implementer of MVVM pattern -- bidirectional data binding pattern
Model: the model layer, where JavaScript objects are represented
View: view layer, which represents DOM (element of HTML operation)
ViewModel: middleware connecting views and data, Vue JS is the implementer of the ViewModel layer of MVVM
There are two ways to introduce vue into the page:
1) Introduce Vue into the project JS file
2) Introduce external network to provide Vue JS file
< script SRC = "external JS" > < / script >, while Vue JS files are slow to load in the United States
CDN: content distribution network
This is an acceleration strategy, which can quickly obtain external resources from the nearest server.
https://www.bootcss.com/
In MVVM architecture, data and views are not allowed to communicate directly. They can only communicate through ViewModel, which defines an Observer observer
- ViewModel can observe the changes of data and update the content corresponding to the view
- ViewModel can monitor the change of view and inform the data of the change
So far, we understand, Vue JS is an implementation of MVVM. Its core is to realize DOM monitoring and data binding
1.1 VM implementation principle
There are two built-in observers in the view dimension
1) observe the change of view: when the view changes, notify the data to change
2) observe the change of data: when the data changes, notify the view to change
-- MVVM realizes bidirectional data binding through VM
<!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> <div id="app"> <span>{{title}}</span> <input type="text" v-model="title" /> </div> </body> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="text/javascript"> new Vue({ el:'#app', data:{ title:'hello vue' } }); </script> </html>
3. Other MVVM implementers
- AngularJS
- ReactJS
- Wechat applet
4. Why use Vue js
Lightweight and small volume is an important index. Vue.js only has more than 20 KB after compression (56KB + after angular compression and 44kb + after react compression)
Mobile first. It is more suitable for mobile terminals, such as Touch events on mobile terminals
Easy to use, stable learning curve and complete documents
It absorbs the advantages of angular (Modular) and react (virtual DOM), and has its own unique functions, such as computing attributes
Open source, high community activity
5,Vue. Two core elements of JS
1) Data driven
When you pass an ordinary JavaScript object to the data type of Vue instance, Vue will traverse all the properties of the object and use Object.defineProperty turns all these properties into getters / setters. Object.defineProperty is a feature in ES5 that cannot shim, which is why Vue does not support IE8 and earlier browsers.
These getters / setters are invisible to the user, but internally they let Vue track dependencies and notify changes when properties are accessed and modified. The problem to note here is that the format of getter/setter is different when the browser console prints data objects, so you may need to install Vue devtools to obtain a more friendly inspection interface.
Each component instance has a corresponding watcher instance object. It will record the properties as dependencies during component rendering. Later, when the setter of the dependency is called, it will notify the watcher to recalculate, so that its associated components can be updated.
2) Componentization
- Each independent interactive area on the page is regarded as a component
- Each component corresponds to a project directory, and various resources required by the component are maintained nearby under this directory
- A page is just a container for components, which can be nested and freely combined (reused) to form a complete page
2, Quick start
1. Just import the js file of vue on the page
Note: cdn is an acceleration strategy, which can provide js files quickly
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.5.17-beta.0/vue.min.js"></script>
2. Bind vue elements in the page
Create a div,id yes app <div id="app"></div>
3. Create vue object and design the content of the object
The vue object is bound to the div whose id is app in the page
<script type="text/javascript"> new Vue({ el:'#app', data:{ title:"hello vue!", args1:"hi!", age:18, flag:true } }); </script>
4. Use interpolation expression in the elements of the page to use the content in vue object
<div id="app"> {{title}} </div>
PS:
1. How to obtain cdn file of vue
https://www.bootcdn.cn/vue/
2. How to use vue in a page
Two parts:
- 1)html: <div id="app"></div>
- 2) A Vue object (instance) is required
3. What are the things in Vue objects and what are they used for?
new Vue({ el:'', Should vue Where is the object bound div upper data:{ } Provide data, which stores key value pairs })
4. In the elements bound by vue in html, the data in vue object is obtained through interpolation expression.
<!DOCTYPE html> <html> <head> <mata charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> Welcome! Age is{{age}}of{{name}} </div> </body> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script> <script type="text/javascript"> new Vue({ // json object, wrapped in curly braces, with key value pairs inside. In js, keys can have no quotation marks, and multiple key value pairs are separated by ',' el:'#app', // element // Where does the data come from? data:{ name:'Xiao Ming', // Later, the data is obtained by sending an ajax request // In the past, data was put into domain objects, so it needs to be developed together age:18 } }); </script> </html>
3, Interpolation expression
The function of interpolation expression is to obtain the content in Model in View
1. Interpolation expression
<div id="app"> {{title}} {{[1,2,3,4][2]}} {{ {"name":"xiaoyu","age":20}.age }} {{sayHello()}} </div>
new Vue({ el:'#app', data:{ title:"hello world!" }, methods:{ sayHello:function(){ return "hello vue"; } } });
2.MVVM bidirectional data binding: v-model
<div id="app"> <input type="text" v-model="title"/> </div>
3. Event binding: v-on
<input type="text" v-on:input="changeTitle"/>
v-on is called binding event. The event is input and the response behavior is changeTitle. That is, when an input event occurs on the input element, the changeTitle method defined in vue will be called
new Vue({ el:"#app", data:{ title:"hello world!" }, methods:{ sayHello:function(){ return "hello vue" }, changeTitle:function(){ console.log("ct");// Write in the log } } })
event.target.value = = the value of the object (input element) of the current event
Note: this refers to the current vue object
So: if you want to use the content in the data in the current vue object in the method, you must add this.
changeTitle:function(event){ this.title = event.target.value; }
4. Simplified version of event binding: use @ to replace v-on:
<input type="text" @input="changeTitle" />
5. Attribute binding: v-bind
All attributes in html cannot use interpolation expressions
<a href="{link}}">baidu</a> new Vue({ el:"#app", data:{ title:"hello world!", link:"http://www.baidu.com" }, })
The above method is wrong. You can use binding attribute binding to solve it:
If you want to use the content of vue object for attributes in html elements, you have to use v-bind for attribute binding
<a v-bind:href="link">baidu</a> Can be abbreviated to a colon <a :href="link">baidu</a>
6 v-once instruction
Indicates that the data of this element only appears once, and the modification of data content does not affect this element
<p v-once>{{title}}</p>
7 v-html
It's like innerHTML
<p v-html="finishedlink"></p> new Vue({ el:"#app", data:{ title:"hello world!", link:"http://www.baidu.com", finishedlink:"<a href='http://www.baidu. Com '> Baidu < / a >“ } })
8 v-text
Plain text output
<p v-text="finishedlink"></p>
PS:
The difference expression is used in the elements bound in html. The purpose is to obtain the attributes and methods in vue object through difference expression.
Syntax format: {content of vue}}
Note: the difference expression cannot be written in the html tag and cannot be used as part of the value of the attribute.
Where are the attributes in the vue object provided?
new Vue({
Data: {} < = = this data provides properties
})
Where are the methods in the vue object provided?
new Vue({
methodsd: {< = = the methods provide methods
sayHi:function(){
alert("hello vue");
}
}
})
In addition, the difference expression can also be used as follows:
<div> {{[0,1,2,3,4][1]}}<br/> {{ {name:'xiaoming',age:20}.name }} </div>
<!DOCTYPE html> <html> <head> <mata charset="UTF-8"> <title>Difference expression</title> </head> <body> <div id="app"> Please enter your major:<input type="text" v-model="major"/> ========================<br/> I am a{{major}}Programmers {{[0,1,2,3,4][1]}}<br/> {{ {name:'xiaoming',age:20}.name }} {{sayHi()}} </div> </body> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script> <script type="text/javascript"> new Vue({ el:'#app', data:{ major:"java" }, methods:{ sayHi:function(){ // alert('HELLO VUE!'); return "hello vue"; } } }); </script> </html>
Keywords in Vue
These keywords are attributes in the tags of html pages
1.v-model: bind the value value of the tag with the data attribute value in the vue instance
Please enter your major:<input type="text" v-model="major"/> new Vue({ el:'#app', data:{ major:"java" } })
2.v-on
Bind the function defined in vue by matching with the specific event name
<!-- Please enter your major:<input type="text" v-on:input="changeMajor()"/> --> Please enter your major:<input type="text" v-on:click="changeMajor()"/> new Vue({ el:'#app', data:{ major:"java" }, methods:{ changeMajor:function(){ console.log("change major"); } } });
There is an error in the following code. changeMajor cannot be distinguished
Please enter your major:<input type="text" v-on:click="changeMajor"/> new Vue({ el:'#app', data:{ major:"java", changeMajor:"hello" }, methods:{ changeMajor:function(){ console.log("change major"); } } });
Supplementary knowledge:
(1)event.target.value: for example, in the response function, you can specify to use the built-in parameter object of event. This object represents the current event, which can be accessed through event target. Value to get the value of the current event object
(2) Usage of this: This indicates the current Vue object "new Vue()", which can be accessed through this To call the properties and methods of the current Vue object
(3)v-on can also be abbreviated as: v-on: input = "" < = = > @ input = ""
Please enter your major:<input type="text" v-on:input="changeMajor"/> <!-- <input type="text" @input="changeMajor"/> --> new Vue({ el:'#app', data:{ major:"java", }, methods:{ changeMajor:function(event){ // console.log(event.target.value); $this.major = event.target.value; } } });
3.v-bind
The difference expression cannot be written in the attribute of html tag. If you want to use the attribute in vue as the attribute content of html tag, you can bind the attribute through v-bind.
new Vue({ data:{ link:"http://www.baidu.com" } }) <a v-bind:href="link"></a> be careful: v-bind It can also be abbreviated:<a :href="link"> <div id="app"> {{link}} <a href="{{link}}">Baidu</a> <a v-bind:href="link">Baidu</a> <a :href="link">Baidu</a> </div> new Vue({ el:'#app', data:{ link:"http://www.baidu.com", }, });
4.v-once
At this time, the interpolation expression of the label is obtained only once, and the subsequent data changes will not affect the interpolation
5.v-html and v-text
v-html uses the value of the attribute in vue as an element of HTML
v-text will only use the value of the attribute in vue as a pure text
<div id="app"> <p>{{link}}</p> <p v-once>{{link}}</p> <input type="text" v-model="link"><br/> <span v-html="mylink"></span> <span v-text="mylink"></span> </div> new Vue({ el:'#app', data:{ link:"http://www.baidu.com", mylink:"<a href='http://www.baidu. Com '> Baidu < / a > ", }, });
4, Events
1. Event binding example
Example 1:
<div id="app"> <button type="button" v-on:click="increase">click</button> <p>{counter}</p> </div> new Vue({ el:"#app", data:{ counter:0 }, methods:{ increase:function(){ this.counter++; } } }):
Example 2:
<p v-on:mousemove="mo">moooooo</p> mo:function(event){ console.log(event); } Example 3: <p v-on:mousemove="mo"> mx:{{x}} my:{{y}} </p> new Vue({ el:"#app", data:{ counter:0, x:0, y:0, }, methods:{ increase:function(){ this.counter++; }, mo:function(event){ this.x = event.clientX; this.y = event.clientY; } } });
2. Parameter transfer
<button type="button" v-on:click="increase(2)">click</button> methods:{ increase:function(step){ this.counter+=step; } }
Pass multiple parameters:
<button type="button" v-on:click="increase(2,event)">click</button>
3. Stop mouse event
<p v-on:mousemove="mo"> mx:{{x}} my:{{y}} --<span v-on:mousemove="dummy">Stop mouse event</span> </p> dummy:function(event){ event.stopPropagation(); } Another way:<span v-on:mousemove.stop>Stop mouse event</span>
4. Event modifier
Prompt when entering enter
<input type="text" v-on:keyup.enter="alertE" />
Prompt when entering spaces
<input type="text" v-on:keyup.space="alertE" />
PS:
Events in Vue
1. How to use events in Vue
2. Event parameter transfer
It is divided into three parts:
Parameter setting: < button type = "button" @ Click = "addbtnfn2 (2)" > add 2 < / button >
Parameter: addbtnfn2:function(step)
Reference: this count+=step;
<div id="app"> {{count}}: {{count>10 ? 'Greater than 10' : 'Not more than 10'}}<br/> <button type="button" @click="addbtnfn">increase</button> <button type="button" @click="relsbtnfn">reduce</button> <input type="text" v-model="mystep"><br/> <button type="button" @click="addbtnfn2(2)">Add 2</button> <button type="button" @click="relsbtnfn2(2)">Decrease 2</button> <p v-on:mousemove="mymo"> Today is Monday!!! {{x}}<br/> {{y}}<br/> <span @mousemove="mystopmo">Event to stop mouse movement</span><br/> <span @mousemove.stop>Event 2 for stopping mouse movement</span> </p> </div>
new Vue({ el:'#app', data:{ count:0, mystep:1, x:0, y:0 }, methods:{ addbtnfn:function(){ // this.count+=1; // count++; / / error // this.count++; // this.count+=this.mystep; / / mystep string, problem // this.count+=this.mystep-0; / / feasible this.count+=1; }, relsbtnfn:function(){ // this.count--; this.count-=this.mystep; }, addbtnfn2:function(step){ this.count+=step; }, relsbtnfn2:function(step){ this.count-=step; }, mymo:function(event){ this.x = event.clientX; this.y = event.clientY; // console.log(event); }, mystopmo:function(event){ event.stopPropagation(); } } });
3. Event modifiers in Vue
@click.stop: stop the propagation of click events
@mousemove.stop: prevents the mouse from moving to the event
@keyup.space: when the space bar pops up
<div id="app"> <input type="text" @keyup="mykeyupfn"> <input type="text" @keyup.entry="mykeyupfn"> <input type="text" @keyup.space="mykeyupfn"> </div>
new Vue({ el:'#app', data:{ }, methods:{ mykeyupfn:function(){ console.log("hello vue!"); } } });
5, vue changing content -- Virtual dom and diff algorithm
1. Interpolation expression
Example 1:
{{ count>10 ? "Greater than 10", "Less than 10"}}
Example 2:
<p>{{result}}</p> new Vue({ el:"#app", data:{ counter:0, result:"" }, methods:{ increase:function(step){ this.counter+=step; this.result=this.counter>10?"Greater than 10":"Not more than 10"; } } })
2. Calculation attribute: calculated
1) What are calculated properties
The key point of calculating attribute is attribute (attribute is a noun). Firstly, it is an attribute. Secondly, this attribute has the ability of calculation (calculation is a verb). Here, calculation is a function; Simply put, it is an attribute that can cache the calculation results (convert the behavior into a static attribute), that's all
2) Differences between calculation attributes and methods
Full HTML
<!DOCTYPE html> <html> <head> <mata charset="UTF-8"> <title>Layout calculation properties</title> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script> </head> <body> <div id="vue"> <p>Method to call the current time:{{currentTime1()}}</p> <p>Calculation properties of current time:{{currentTime2}}</p> </div> </body> <script type="text/javascript"> var vm = new Vue({ el:'#vue', data:{ message:'Hello Vue' }, methods:{ currentTime1:function(){ return Date.now(); } }, computed:{ currentTime2:function(){ this.message; return Date.now(); } } }); </script> </html>
explain:
- methods: define the method, and the calling method uses currentTime1(), which needs parentheses
- computed: defines the calculation attribute. The calling attribute uses currentTime2 without parentheses; this.message is changed so that currentTime2 can observe data changes
Note: methods and computed cannot have the same name
3) Test effect
Look carefully at the illustration and observe the difference
4) Conclusion
When calling a method, it needs to be calculated every time. Since there is a calculation process, there must be system overhead. What if the result does not change frequently?
At this point, you can consider caching the results, which can be easily achieved by using computational properties
The main feature of computing attribute is to cache the infrequently changed computing results, so as to save our system overhead
3. Usage of watch: Monitor
watch is used to monitor parameter changes and call functions. newVal is the new value of the parameter and oldVal is the old value of the parameter
new Vue({ el:"#app", data:{ counter:0, result:"" }, methods:{ increase:function(step){ this.counter+=step; // this. result=this. counter>10? "Greater than 10": "not greater than 10"; }, getResult:function(){ return this.counter>10?"Greater than 10":"Not more than 10"; } }, computed:{ getResultComputed:function(){ return this.counter>10?"Greater than 10":"Not more than 10"; } }, watch:{ } })
6, Vue change style
1. Dynamic binding of class
v-bind:class="{red:attachRed}"
The key name is the class name and the key value is Boolean. If it is true, the specified class name will be bound to the element. If it is false, it will not be bound.
<head> <mata charset="UTF-8"> <title>afternoon</title> <style> .demo{ width:100px; height:100px; background-color:gray; display:inline-block; margin:10px; } .red{background-color:red;} .green{background-color:green;} .blue{background-color:blue;} </style> </head> <body> <div id="app"> {{attachRed}} <div class="demo" @click="attachRed!=attachRed" v-bind:class="{red:attachRed}"></div> <div class="demo"></div> <div class="demo"></div> </div> </body> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script> <script> new Vue({ el:"#app", data:{ attachRed:false } }); </script>
2. Add computed
<div class="demo" :class="divClasses"></div> new Vue({ el:"#app", data:{ attachRed:false }, computed:{ divClasses:function(){ return { // Returns a json object red:thie.attachRed, blue:!this.attachRed } } } })
3. Embodiment of two-way binding
You can set the div class by entering the color in input
<div id="app"> <input type="text" v-model="color"/> {{attachRed}} <div class="demo" @click="attachRed!=attachRed" v-bind:class="{red:attachRed}"></div> <div class="demo"></div> <div class="demo" :class="divClasses"></div> <div class="demo" :class="color"></div> </div> <script> new Vue({ el:"#app", data:{ attachRed:false, color:"green" } }) </script>
4. Operation of multiple styles
.red{background-color:red;color:white;} <div class="demo" :class="[color,{red:attachRed}]">hahaha</div>
5. Set style through style
<div class="demo" :style="{background-color:color}"></div>
Set the value of div's style attribute, put json object in style, the key is humped, and the value is the variable color
6. Use computed to set the style
<div class="demo" :style="myStyle"></div> <input type="text" v-model="width" /> new Vue({ el:"#app", data:{ attachRed:false, color:"green", width:100 }, computed:{ divClasses:function(){ return { red:this.attachRed, blue:!this.attachRed }, myStyle:function(){ return { backgroundColor:this.color, width:this.width+"px" } } } } })
7. Set multiple styles of the style attribute
<div class="demo" :style="[myStyle,{height:width*2+'px'}]"></div>
PS:
computed calculated attribute
Some commonly used functions can be cached, and the process (result) in the cache can be directly used when calling, so as to improve efficiency.
Note: Although functions are stored in computed, when calling, the thing in computed is an attribute. Therefore, you cannot use '()' when calling, because () is calling a function, not a property.
watch monitoring properties
By binding a function to the attribute in watch, the function will be called when the value of the attribute changes. Two parameters can be received when calling. The first parameter is the value after the attribute is changed, and the second parameter is the value before the attribute is changed.
<div id="app"> {{title}} <input type="text" v-model="title"/> </div> <script type="text/javascript"> var vm = new Vue({ el:'#app', data:{ title:'hello Vue' }, watch:{ title:function(newValue,oldValue){ // console.log("title changed"); console.log(newValue+":"+oldValue); } } }); </script>
Vue change style
1. Bind the attribute value in vue to the class attribute of html element to get the dynamic binding of style
new Vue({ el:'#app', data:{ temp:false }, });
<div :class="{red:temp}"></div>
If temp=true = = < div class = "red" > < / div >
If temp=false = = < div > < / div >
2. Return an object through computed, where there are multiple key value pairs
<div id="app"> <!-- <div v-bind:class="{{red:true}}" class="mydiv"></div> report errors--> <!-- <div v-bind:class="{red:true}" class="mydiv"></div> --> <div v-bind:class="{red:temp}" class="mydiv"></div> <div :class="myClassType" class="mydiv"></div> <div class="mydiv"></div> <button type="button" @click="temp=!temp">Point me</button> </div> // v-bind:class="{red:true}" ==>class="red" new Vue({ el:'#app', data:{ temp:false }, computed:{ myClassType:function(){ return { red:this.temp, mywidth:this.temp } } } });
3. Change the style by directly binding the attributes in vue
<div :class="mycolor" class="mydiv"></div> <input type="text" v-model="mycolor"> new Vue({ el:'#app', data:{ temp:false, mycolor:'green' }, })
4. Use a combination of multiple styles in html tags
.red{background-color:red;} .yellow{background-color: yellow;} .green{background-color:green;} .blue{background-color:blue;} .mywidth{width:600px;} <div :class="[mycolor,mv]" class="mydiv"></div> Note: it cannot be written like this:<div :class="mycolor" :class="mv" class="mydiv"></div> new Vue({ el:'#app', data:{ temp:false, mycolor:'green', mv:'mywidth' }, })
5. Specify the value of style attribute in the embedded css style
<div style="background-color: aquamarine" class="mydiv"></div> <div :style="{backgroundColor: bc}" class="mydiv"></div> be careful: style Quoted vue Therefore, it is a key value pair, so braces are required, and the key of the object cannot appear"background-color",It should be changed to backgroundColor new Vue({ el:'#app', data:{ bc:'blue' // document.getElementById('#sp').style.backgroundColor }, })
6. Use the combination (array) of multiple styles in style
<div id="app"> <div :style="[myStyle,{height:myHeight*2+'px'}]" class="mydiv"></div> <button type="button" @click="temp=!temp">Point me</button> Color:<input type="text" v-model="bc"><br/> Height:<input type="text" v-model="myHeight"> </div> new Vue({ el:'#app', data:{ temp:false, bc:'blue', myHeight:300 }, computed:{ myStyle:function(){ return { backgroundColor:this.bc, } } } });
The core of Vue: virtual DOM and diff algorithm
Ordinary js file
1) Transform HTML into a DOM tree
2)document.getElementById to find the element and modify the node on the DOM tree. This method is inefficient
vue
1) Made a deep optimization, using virtual DOM technology
2)vue directly modifies the DOM element on the page. At this time, the element is a virtual dom
3) The direct difference between the virtual dom and the original dom is calculated by diff algorithm, and then the virtual dom is modified based on the original dom to improve efficiency
The core of vue efficiency is the virtual dom and diff algorithm. vue does not modify the dom tree to achieve the effect of modification, but directly changes that element on the page.
At this time, this element is a virtual dom, so how can vue change it?
Through the diff algorithm, the difference between the modified virtual dom and the modified virtual dom is calculated, and then the virtual dom is modified on the original basis, so the efficiency is greatly improved.