Writing in the front
The study notes of Vue family bucket refer to the Vue framework teaching videos and Vue official teaching documents of Silicon Valley
Introduce the Vue
Vue is a JS library, its key word is progressive: Vue library is divided into core library and plug-in library, the core library can meet the basic needs. Plug-in libraries are added by users when they need them, which is a “progressive” concept. The function of Vue library lies in the dynamic construction of the front-end interface: the background data in the foreground dynamic display rendering.
Vue’s association with other JS frameworks
- Uses Angular templates and data binding techniques
- React componentization and virtual DOM techniques are borrowed
The characteristics of the Vue
The MVVM pattern
What is a MVVM? That is M(data Model) +V(View View)+VM(Vue instance object ViewModel). In conjunction with the official starter tutorial, the MVVM pattern elements refer to:
The specific MVVM mode of Vue is shown below:
DOM listening and data binding enable view-to-Model reads and writes and Model-to-view reads and writes
Vue plugin
Basic use of Vue
Template syntax
Double brace expression
The double brace expression is used for text interpolation. The js variable value can be inserted into an HTML element using {{value}} in HTML text.
<p>{{name}}</p>
<p>{{name.toUpperCase()}}</p>
<p v-text="name"></p>
<p v-html="name"></p><! The difference between innerHTML and innerText is that the innerHTML parses the value into HTML.
Copy the code
Forced data binding
Mandatory data binding creates a bridge between the ** attributes of DOM elements and the VM, as follows:
<h2>2 Enforce data binding</h2>
<img v-bind:src="imgUrl">
<img :src="imgUrl">
Copy the code
ImgUrl is a user-defined JS variable in data in the VM that holds the SRC address of the image.
Bind event listener
You can bind event listeners to DOM elements (click events, etc.) :
<h2>3 Bind event listening</h2>
<button v-on:click="test"></button>
<button @click='test2(msg)'></button>
Copy the code
Test is a user-defined JS method in methods in the VM.
Calculation and Monitoring
Calculate attribute
When we need to evaluate variables in data to get new values, we use computed attributes in the VM. In a computed method definition, the return value is the value that we want the variable to compute, and when the corresponding variable changes, the calculation of the property is triggered. Here is an example (full name = first name + first name) :
<div id="demo">Last name:<input v-model="lastName" type="text"><br>Name:<input v-model="firstName" type="text"> <br>Name:<input v-model="fullName" type="text"><br>
</div>
Copy the code
var vm = new Vue({
el: '#demo'.data: {
firstName: 'kobe'.lastName: 'bryant',},computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
})
Copy the code
Evaluate properties vs methods
We can define the same function as a method instead of a calculated property. In the example above, we can define the fullName function in the methods component to achieve the same effect. The difference, however, is that computed attributes are cached based on their reactive dependencies. Computed properties are stored in the cache and are reevaluated only when the associated reactive dependencies change. As a result, fewer resources are required to evaluate the properties when rerendering.
monitoring
As in the above example, we can also implement monitoring (watch), by monitoring the change of a variable callback, they can achieve the same effect, use the following example:
<div id="demo">Last name:<input v-model="lastName" type="text"><br>Name:<input v-model="firstName" type="text"> <br>Name (one-way 2) :<input v-model="fullName1" type="text"><br>
</div>
Copy the code
var vm = new Vue({
el: '#demo'.data: {
firstName: 'kobe'.lastName: 'bryant'.fullName1: 'kobe bryant',},watch: {
firstName: function (newval, oldval) {
this.fullName1 = newval + ' ' + this.lastName
},
lastName: function (newval, oldval) {
this.fullName1 = this.firstName + ' ' + newval
}
}
})
Copy the code
Calculate getters and setters for properties
A calculated property has only getters by default, but a setter callback can also be provided if needed, which is called immediately when the calculated property changes:
computed: {
fullName2: {
get() {
return this.firstName + ' ' + this.lastName
},
set(value) {
this.firstName = value.split(' ') [0]
this.lastName = value.split(' ') [1]}}}Copy the code
By evaluating the getters and setters for the property, we can easily make two-way changes to the associated variables.
Class and style binding
Class lists and inline styles for manipulating elements are a common requirement for data binding. Vue.js is specifically enhanced when v-bind is used for class and style. The result of an expression can be an object or an array in addition to a string.
A class of binding
The class binding is dynamic, and it can be combined with the HTML class (static). We can use static to specify fixed styles, and class binding to implement dynamic class changes. They don’t overwrite, they merge. Such as:
<p class="fontSize" v-bind:class="Pcolor">This is a paragraph</p>
Copy the code
String expression
For a simple example, click the button to toggle class:
<div id="color">
<h2>The change of the style</h2>
<p v-bind:class="Pcolor">This is a paragraph</p>
<button @click='update'>update</button>
</div>
Copy the code
var ColorVm = new Vue({
el: '#color'.data: {
Pcolor: 'redFonts',},methods: {
update() {
this.Pcolor = 'blueFonts'}}})Copy the code
Object expression
An example:
<p :class='ObjClass'>Class binds a JS object</p>
Copy the code
data: {
Pcolor: 'redFonts'.ObjClass: {
fontSize: true.redFonts: true //fontSize and redFonts are class names}},Copy the code
Array expressions (less commonly used)
An example:
<div v-bind:class="[activeClass, errorClass]"></div>
Copy the code
data: {
activeClass: 'active'.errorClass: 'text-danger'
}
Copy the code
Style binding
Example:
<div v-bind:style="styleObject"></div>
Copy the code
data: {
styleObject: {
color: 'red'.fontSize: '13px'}}Copy the code
Conditions apply colours to a drawing
V if and V else-if and V else
The V-if directive is used to conditionally render a piece of content. This content will only be rendered if the expression of the directive returns true,v-else and V-else need to be used with V-if.
<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else-if="horrible">Vue is horrible!</h1>
<h1 v-else>Oh no 😢</h1>
Copy the code
v-show
Another option for displaying elements by conditions is the V-show directive. The usage is roughly the same:
<h1 v-show="ok">Hello!</h1>
Copy the code
The difference between the two conditions
V-if hides the element by removing it from the DOM, v-show hides the element by adding display= None.
The list of rendering
V-for can render a list, as an example, as follows: V-for can render a list, with each LI tag containing the user’s index, name, and age, as well as a delete button and an update button (to update the current LI to the specified information). The implementation process is as follows:
<div id="demo">
<h2>V-for traversal number group</h2>
<ul>
<li v-for="(person,index) in persons">
{{index}}----{{person.name}}----{{person.age}}
---<button @click='del(index)'>delete</button>
---<button @click='update(index)'>update</button>
</li>
</ul>
</div>
<script>
new Vue({
el: '#demo'.data: {
persons: [{name: 'Tom'.age: 16 },
{ name: 'Jack'.age: 17 },
{ name: 'Rose'.age: 18 },
{ name: 'Bob'.age: 19},].newPerson: {
name: 'Daddy'.age: '40'}},methods: {
del(index) {
this.persons.splice(index, 1)},update(index) {
this.persons[index] = this.newPerson
}
},
})
</script>
Copy the code
But the update feature doesn’t work! Using the vue debug tool, we found that the Persons array is not updated in response to the update. Did I learn it wrong? In this case, the contents of Persons have changed: This. persons[index] = this.newPerson, but Person points to the same array, so this statement does not trigger view changes.
But… Why does delete work? Splice does not return the new array but deletes the values in the original array. A look at the VUE documentation shows that this involves array update detection.
Array update detection problem
Change the way
Vue wraps the change methods of the array being listened on, so they will also trigger view updates. These covered methods include:
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
So back to the example, we change the update code to this.persons.splice(index, 1, this.newperson).
Replace the array
The above methods make changes to arrays, but there are ways to replace arrays directly — these methods return new arrays, such as filter(), concat(), and slice(). You might think that this would cause Vue to discard the existing DOM and re-render the entire list. Fortunately, this is not the case. Vue implements some clever heuristics to maximize the reuse of DOM elements, so it is very efficient to replace an array with one containing the same elements.
V-for can also iterate over objects as follows:
<h2>V-for traverses the object</h2>
<ul>
<li v-for="(item,index) in persons[0]" :key="index">
{{index}}----{{item}}
</li>
</ul>
Copy the code
The role of the key attribute
Key is added in v-for to improve performance. When new values are inserted into the array bound by V-for, resulting in page rendering and array re-rendering, no key value is equivalent to array insertion. The virtual DOM will render array elements with index changes during diff comparison. After the addition of key, the array is equivalent to a linked list, and the insertion efficiency is significantly improved.
List searching and sorting
Here follow the silicon Valley tutorial knocked a case:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<script src="vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="demo">
<input type="text" v-model="searchName">
<ul>
<li v-for="(person,index) in Filterpersons">
{{index}}----{{person.name}}----{{person.age}}
</li>
</ul>
<button @click='setOrderType(1)'>Age ascending</button>
<button @click='setOrderType(2)'>Age in descending order</button>
<button @click='setOrderType(0)'>Originally the order</button>
</div>
<script>
var input = document.querySelector('input')
new Vue({
el: '#demo'.data: {
searchName: ' '.persons: [{name: 'Tom'.age: 16 },
{ name: 'Jack'.age: 17 },
{ name: 'Rose'.age: 18 },
{ name: 'Bob'.age: 15 },
{ name: 'Jessica'.age: 14}].orderType: 0.//0 indicates normal sorting, 1 indicates ascending sorting, and 2 indicates descending sorting
},
computed: {
Filterpersons() {
// The required variables
const { searchName, persons, orderType } = this
// Search box filtering
let fpersons = persons.filter(person= > person.name.indexOf(searchName) >= 0)
// Sort processing
if(orderType ! = =0) {
orderType == 1 ? fpersons.sort(function (a, b) {
return a.age - b.age;
}) : fpersons.sort(function (a, b) {
returnb.age - a.age; })}return fpersons
}
},
methods: {
setOrderType(type) {
this.orderType = type; }}})</script>
</body>
</html>
Copy the code
But there is a small bug that is not understood. When I put the sorting code before the search box filter, the function of sorting into the original order will not work. , that is:
Filterpersons() {
// The required variables
const { searchName, persons, orderType } = this
let fpersons = persons
if(orderType ! = =0) {
orderType == 1 ? fpersons.sort(function (a, b) {
return a.age - b.age;
}) : fpersons.sort(function (a, b) {
returnb.age - a.age; })}return fpersons.filter(person= > person.name.indexOf(searchName) >= 0)}Copy the code
The event processing
Binding to monitor
Binding listeners have been written about before, and here is how the event parameter is passed in for event listeners. When no arguments are passed to the listening callback:
<button @click='test'>test</button>
Copy the code
test(event) {
alert(event.target.innerHTML)
}
Copy the code
Otherwise you need to pass in the HTML code with $event:
<button @click='test(number,$event)'>test</button>
Copy the code
test(number,event) {
alert(number,event.target.innerHTML)
}
Copy the code
Event modifier
PreventDefault () : event preventDefault() : event preventDefault() : event preventDefault() : Event preventDefault() : Event preventDefault() : Event preventDefault()) : Event preventDefault() : Event preventDefault() : Event preventDefault()) : Event preventDefault() : Event preventDefault()) : Event preventDefault() : Event preventDefault()) : Event preventDefault() : Event preventDefault()) : Event preventDefault() : Event preventDefault()) As follows:
<h2>Event modifier</h2>
<div style='width: 200px; height: 200px; background-color: yellow; ' @click='Outer'>
<div style='width: 100px; height: 100px; background-color: blue; ' @click.stop='Inner'>
</div>
</div>
<a href="www.baidu.com" @click.prevent>This link will not jump</a>
Copy the code
Vue provides the following event modifiers:
- .stop
- .prevent
- .capture
- .self
- .once
- .passive
Key modifier
When listening for keyboard events, we often need to check for detailed keystrokes. Vue allows v-ONS to add key modifiers when listening for keyboard events:
<! -- call 'vm.submit()' only if 'key' is' Enter '-->
<input v-on:keyup.enter="submit">
Copy the code
Gospel of lazy people, no longer need to write judgment conditions in JS…
Input binding for the form
For form elements — text/ Textarea,radio (radio),checkbox (multiple), SELECT (drop-down) — v-model can be used to create two-way data binding, as shown in the following example:
<body>
<form action="" id="demo">
<span>User name:</span>
<input type="text" name="" id="" v-model="usrname">
<span>Password:</span>
<input type="text" name="" id="" v-model="pwd">
<span>Gender:</span>
<input type="radio" value="Female" id="female" v-model='sex'>
<label for="female">female</label>
<input type="radio" value="Male" id="male" v-model='sex'>
<label for="male">male</label>
<input type="submit" value="Submit" @click.prevent='onSubmit'>
</form>
<script>
new Vue({
el: '#demo'.data: {
usrname: ' '.pwd: ' '.sex: ' ',},methods: {
onSubmit(event) {
alert(this.$data.toString())
}
}
})
</script>
</body>
Copy the code
V-model is essentially a combination of two commands: v-bind:value + V-on :input
Modifier for v-model
- Lazy: Data is not updated until out-of-focus is entered
- Number: limits the input to a number
- Trim: Automatically removes Spaces at the beginning and end of input
Vue life cycle
Taking the official sample diagram, you can divide the life cycle into three parts: initialization, update, and death. The rounded red boxes represent callback functions called during the lifecycle and can be defined in the Vue instance, officially calledLifecycle hook. Common hooks are Mounted and beforeDestroy.