Ability not matched with ambition is the root of all trouble. The world is fair, you want to get, you have to learn to give and insist. Everyone is through their own efforts, to determine what life looks like.Copy the code
Main Contents of this issue
- Instructions:
- Bidirectional binding:
- Binding style:
- Custom instruction:
I. Instructions:
-
Create multiple elements of the same structure over and over again based on the contents of the array: V-for
V -for=”(value, I) of array/object/string “>
(2). Principle: When new Vue() scans here for the first time, or the content of the dependent array changes:
A. Automatic traversal of arrays or objects…
B. Each time a member is traversed
1). Give the value of the member to the value variable before of; 2) give the subscript position of the member to the I variable before ofCopy the code
C. Repeatedly create the HTML element where v-for is located and replace the values of value and I with possible changes in the element.
D. Value and I variables can be bound on the current element where v-for is located and on all children of the current element.
(3). Emphasis on:
A. v-for must be written on the element to be generated repeatedly, not on the parent element: for example, if multiple elements of the same ul are generated, v-for should be written on the child element li. But the first variable is always followed by the element value, the second variable is always followed by the subscript (4). In fact, Vue v-forof, unified JS forof and forin function! It can traverse both numeric subscripts and custom subscripts.Copy the code
(5). Problem: Because V-for repeatedly generates multiple HTML elements, in addition to different content, the element itself is no difference! As a result, v-for cannot find out exactly which copy of the HTML element to modify in case an element in the dependent array changes. So V-for chose the dumbest option, deleting all the elements, iterating through the array, and recreating all the copies — inefficient
Result: Each copy of an HTML element has a key=” subscript “attribute. When an operation is performed on an element in an array, vue finds an element with key=” index “based on the subscript and modifies only this element, leaving the other elements unaffected. — High efficiency!
(7) summary: Contempt: Why v-for must add :key?
A. Avoid reconstructing all HTML elements when modifying an array member. B. If you add :key, you only need to modify one copy of an ARRAY element at a time -- efficientCopy the code
(8). Example: Use V-for to iterate over groups and objects
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app"> <ul> <! Because we are repeatedly generating multiple li elements of the same structure based on the contents of the tasks array, we should use v-for--> <li v-for= on the li element"(value,i) of tasks" :key="i"> <! {{I +1}}. {{value}} </li> </ul> <! <ul> <li v-for="(value,key) of lilei" :key="key">{{key}}: {{value}}</li>
</ul>
</div>
<script>
new Vue({
el:'#app', data:{// There is a list of tasks that you want to display on the page. Tasks :["Eat"."Sleep"."Shine the light."],//.length=3
// 0 1 2
lilei:{
sname:"Li Lei",
sage:11,
className:Class 2, Grade 1}}}) </script> </body> </ HTML >Copy the code
9). In fact, v-for can also count: it can repeatedly generate a specified number of copies of HTML elements based on a single number, and count from 1 to the given number
A. < element v-for=" I of numbers "> b. Principle: When new Vue() scans here for the first time, or when the dependent value changes: 1). 2). Each time a copy is created, the number is saved to the variable before "of". 3). The variable I in the current element and its children can be used for binding.Copy the code
(10). Example: Use V-for to generate paging buttons
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="js/vue.js"></script>
<style>
#pages{ list-style: none; }
#pages>li{
float:left;
padding:5px 10px;
border:1px solid #aaa;
margin:0 5px;
}
</style>
</head>
<body>
<div id="app"> <! > <ul id= <ul id="pages">
<li v-for="i of pageCount" :key="i">{{i}}</li>
</ul>
</div>
<script>
new Vue({
el:"#app", data:{pageCount:5,// there is always a variable to save the total number of pages}}) </script> </body> </ HTML >Copy the code
-
Binding event: V-ON
< element V-on: event name =” event handler ()”>
< element on event name =” event handler ()”>
(3). Important difference: This in VUE event handler no longer refers to the element that triggered the event. Instead, it points to the entire new Vue() object!
(4). Abbreviations:
< element @event name =” event handler ()”> < element @event name =” event handler ()”>
B. If the event handler does not have any argument values, omit ():< element @event name =” event handler “>
(5). Actually: vue event handlers can pass parameters!
A. < element @ Event name ="Event handler (list of argument values)"> methods:{event handlers (parameter list){... }}Copy the code
B. Example: click which div, which div shout who pain!
<! DOCTYPE html>Copy the code
` ` `Copy the code
(6). Actually: Event objects are also available in VUE: 2 kinds
< element @ event name =" event handler "> methods:{event handler (e){... }} 3). Problem: If you need to pass in both the argument value and the event object, the argument value and the event object e pass in the position of the collision! < element @ event name =" event handler (argument value)"> Event methods:{event handler (e){... < element @ event name =" event handler (argument value)"> event methods:{event handler (parameter 1, e){... }} Because the event object can only be passed to the first parameter by default, no other parameters will be passed. < element @ event name =" event handler (argument value)"> Event methods:{event handler (e, parameter 1){... }} Because the first parameter is not smart enough to automatically give the second parameter, still give the first parameter, still conflict with the event 6). How to get the mouse position in Vue:Copy the code
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="js/vue.js"></script>
<style>
#app>div{
width:300px;
height:100px;
}
#app>div:hover{
box-shadow:0 0 5px red
}
</style>
</head>
<body>
<div id="app"> <! Click on a location in any div and call it pain! --> <div id="d1" style="background-color:#aaf" @click="say"></div>
<div id="d2" style="background-color:#ffa" @click="say"></div>
</div>
<script>
new Vue({
el:"#app", data:{}, methods:{// Because to obtain the mouse click position, we must add parameter e //event // ↓ say(e){alert('${e.offsetX}.${e.offsetY}Position hurts! }}}) </script> </body> </ HTML >Copy the code
B. If both the argument value and the event object are passed: use the vue keyword $event
< element @ event name =" event handler (argument, $event)"> methods:{event handler (parameter 1, e){... }} Note: $event and argument values can be swapped. $event Gets the event object at any position in the argument list. Not affected by location!Copy the code
C. Example: If both a custom argument value and an event object are passed:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="js/vue.js"></script>
<style>
#app>div{
width:300px;
height:100px;
}
#app>div:hover{
box-shadow:0 0 5px red
}
</style>
</head>
<body>
<div id="app"> <! If you need to pass in both the argument value and the event object --> <! -- DOM event--> <! <div id="d1" @click="say($event,'d1')" style="background-color:#aaf"></div> <! -- DOM event--> <! <div id="d2" @click="say($event,'d2')" style="background-color:#ffa" ></div>
</div>
<script>
new Vue({
el:"#app", data:{}, methods:{// Two arguments are passed to the event handler, so when we define the event handler in methods, we must define two parameters corresponding to say(e, id){alert('${id}the${e.offsetX}.${e.offsetY}Position hurts! }}}) </script> </body> </ HTML >Copy the code
-
Prevent users from seeing {{}} briefly:
(1). Problem: If the network speed is not good, js code is slow to download, users may briefly see the {{}} syntax on the page! – embarrassed!
(2). Solution: two ways
A. Use the V-cloak attribute:
1).2: I. Define an attribute selector at the same location on the page: [V-cloak]{display: None} Add a V-cloak attribute to a page with {{}} content, without any property value 2). The v-cloak selector works at the moment when the js at the new Vue() is not loaded at the moment. The v-cloak selector works at the moment when the v-cloak and {{}} elements are hidden at the moment. When the new Vue() js file is loaded, the new Vue() will automatically find all the V-cloak properties and remove the V-cloak properties from these elements. These elements with {{}} are displayed! The V-cloak attribute is the name of the built-in vue command. Do not change it at will!Copy the code
B. Replace {{}} with v-text:
1). 1 step: < element v-text=" variable or js expression "> </ element > 2). Principle: When new Vue() scans here for the first time or the dependent variable changes, Vue will first calculate the result of the JS expression in "", and then replace the content of the element with the result. Why is it possible to mask {{}}, because there is no {{}}. 4). Problem: The advantage of {{}} is that you can concatenate a new string display with other written dead strings. With V-text, however, you can't concatenate dead strings with variables or expressions at will. < element V-text =" 'XXXX ${variable or JS expression}' "> </ element >Copy the code
(3). Example: Use v-text and V-cloak to solve the problem of seeing {{}} temporarily:
<! DOCTYPE html>Copy the code
User name: {{uname}}
` ` `Copy the code
-
The content to bind is the HTML fragment: V-HTML
(1). Problem: If you bind an HTML fragment with {{}} or V-text, you don’t give the bound content to the browser to parse, but display it on the page as it is — not what you want
(2). Why: {{}} and V-text are actually equivalent to the DOM. TextContent
(3). Solution: in the future, whenever binding a HTML fragment, should use V-HTML instead of V-text and {{}}}
(4). Why: The underlying version of V-HTML is equivalent to.innerhtml in the DOM
< element V-html =" variable or JS expression "> </ element >
(5). Principle: V-HTML will first give the binding content to the browser to parse, and then show the content of the parsed content replacement element.
(6). Example: Bind HTML fragment content with {{}}, V-text, and V-html respectively
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app">
<h3>{{html}}</h3>
<h3 v-text="html"></h3>
<h3 v-html="html"></h3>
</div>
<script>
new Vue({
el:"#app", data:{HTML: 'from < < <a href="javascript:;"< p style = "max-width: 100%; clear: both; min-height: 1em; > Message '}}) </script> </body> </ HTML >Copy the code
-
Bind only once on first load:
(1). Problem: Some contents displayed on the interface are only updated once when they are first loaded. Little will change after that! If this element is also included in the virtual DOM tree, the virtual DOM tree will be virtually enlarged, which may affect the speed of traversal
(2). Solution: Make this element bind only once when it is first loaded and not added to the virtual DOM tree.
(3). How: < element v-once></ element >
(4). Principle: All elements with V-once are bound only once when they are loaded for the first time, and will not change even if the variable changes afterwards. Because the v-once element is not added to the virtual DOM tree at all.
(5). Advantages: The content in the virtual DOM tree is reduced and the traversal speed is accelerated
(6). Example: Bind the page load completion time with V-once
<! DOCTYPE html>Copy the code
Page load completion time (one-time): {{time}}
Current system time (repeated many times): {{time}}
` ` `Copy the code
-
Prevent {{}} from being compiled in content: V-pre
(1). Special case: {{}} happens to be included in the element content, but does not want to be compiled by Vue, just want to display as is
< element v-pre> XXX {{XXX}} XXX </ element >
(3). Result: Vue does not parse the {{}} in the content into variables or JS expressions, but displays it on the page as is.
(4). Example: Prevent {{}} in content from being compiled:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app"</h3> </div> <script> new Vue({el:"#app"}) </script> </body> </ HTML >Copy the code
***** Bidirectional binding:
- Problem: None of the above 12 binding methods can get the new value entered by the user in the text box on the page!
-
Reason: Because the bindings or directives in the previous 12 were one-way bindings:
(1) one-way binding: only the changes in the program can be automatically sent to the interface, and the changes made by users on the interface cannot be reversed and updated back to the variables in the program. (Only from Model->View, not from View->Model)
-
Solution: Use bidirectional binding anytime you want to see changes made by the user in a form element on the page
(1). Bidirectional binding: it can not only automatically send the changes in the program to the interface, but also update the changes made by the user on the interface back to the variables in the program. (From Model->View, and from View->Model)
-
How to: Usually used to bind form elements, because only form elements can be modified on the page! < form element V-model :value=” custom variable “>
Data :{custom variable: initial value}Copy the code
- Example: click the button to obtain the keyword entered in the text box and perform the search operation
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app"> <! Which of the interfaces can change? The content of the text box may change because the content of the text box is the value attribute. To bind the value of the value attribute, you should use: bind, custom variable named keywords--> <! V->M ->M ->M -> <! -- Where can the find event be triggered? button--> <input v-model:value="keywords"><button @click="search"</button> < div> <script> new Vue({el:"#app"// Since the page needs a keyword variable, we should define a keyword variable in data to support the page data:{keywords:"mac"}, methods:{// Since we need an event handler search() on the page, we need to define a search() function in methodssearch(){// If the keyword received in keywords is not an empty string, the lookup operation is performedif(this.keywords.trim()! = ="") {the console. The log (` lookup${this.keywords.trim()}Related content... ')}}}}) </script> </body> </ HTML >Copy the code
-
Bidirectional binding principle: Based on the one-way binding principle (accessor attribute + virtual DOM tree), the onchange event is automatically bound to form elements
The onchange event is a common DOM event that is meant to trigger automatically when something changes!
-
Example: Simulate bidirectional binding using the @change event and DOM E.target
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app"> <! -- When the contents of the text box change, automatically get the new value in the text box, save to the variable keywords --> <input :value="keywords" @change="change"><button @click="search"</button> < div> <script> new Vue({el:"#app"// Since the page needs a keyword variable, we should define a keyword variable in data to support the page data:{keywords:"mac"}, methods:{// Since we need an event handler search() on the page, we need to define a search() function in methodssearch(){// If the keyword received in keywords is not an empty string, the search operation // is performedif(this.keywords.trim()! = ="") {the console. The log (` lookup${this.keywords.trim()}Related content... ') //}}, // How to get the contents of the current element: DOM e.target change(e){this.keywords=e.target. Value; }}}) </script> </body> </ HTML >Copy the code
-
Problem: Some form elements have fixed values when the user modifies them! Change to other attributes:
For example:
<input type="radio" value="1" name="sex"Male > < inputtype="radio" value="0" name="sex"> femaleCopy the code
-
Solution: Analysis, when the user manipulates these elements, which attribute should it be?
1). For example: if the user selects or unselects radio, the checked property of radio is changed!
2). So: THE V-Model should be bound to the Checked property
<input type="radio" value="Fixed value" name="Group name" v-model:checked="Variable name">
Copy the code
3.) principle:
Radiov-model :checked=” Variable name “V-Model will compare the variable value with the value of the current radio. If the variable value is equal to the value of the current radio, the current radio is selected. Otherwise, if the variable value is not equal to the value of radio, the current radio is not selected
Ii. When the user switches the selected state of radio:
If the current radio is selected, v-Model will automatically transfer the value of the current radio to the program and save it in the variable of data. If the current radio is not selected, then the V-Model does nothing
- Example: Select gender in VUE:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app"> <h3> Your gender is: {{sex}}</h3> <! -- V-model :checked= XXX on both radios when the user selects the gender, and v-model:checked= XXX on both radios. So both radio bindings bind sex --> gender: <label><inputtype="radio" value="1" name="sex" v-model:checked="sex"Male > < / label > < label > < inputtype="radio" value="0" name="sex" v-model:checked="sex"</div> <script> new Vue({el:"#app"Data :{sex:1}}) </script> </body> </ HTML >Copy the code