conditional rendering
-
v-if
- Writing method:
- v-if = "expression"
- v-else-if = "expression"
- v-else = "expression"
- Applicable to: scenes with low switching frequency
- Features: DOM elements that are not displayed are removed directly
- Note: v-if can be used together with: v-else-if and v-else, but the structure must not be "broken"
- Writing method:
-
v-show
- Writing method: v-show = "expression"
- Applicable to: scenes with high switching frequency
- Features: do not show that DOM elements have not been removed, just hide them with styles
- Note: when using v-if, elements may not be available, but must be available when using v-show
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>conditional rendering </title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <!-- Prepare a container --> <div id="app"> <h2>Current n The values are:{{n}}</h2> <button @click="n++">Point me n+1</button> <!-- use v-show Do conditional rendering --> <h2 v-show:"false">Welcome to{{name}}</h2> <h2 v-show:"1 === 1">Welcome to{{name}}</h2> <!-- use v-if Do conditional rendering --> <h2 v-if:"false">Welcome to{{name}}</h2> <h2 v-if:"1 === 1">Welcome to{{name}}</h2> <!-- v-else and v-else-if --> <div v-if="n===1">Dali</div> <div v-else-if="n===2">Xiamen</div> <!-- <div>@</div> Interruptions are not allowed --> <div v-else-if="n===3">Taiwan</div> <div v-else>Taiwan</div> <!-- v-if And template Combined use of template Just a template structure will not be parsed into the screen--> <!-- v-show Not with template Combined use of --> <template v-if="n===1"> <h2>Hello</h2> <h2>Tongfu Inn</h2> <h2>Wulin biography</h2> </template> </div> </body> <script type = "text/javascript"> Vue.config.productionTip = false // Create Vue instance const vm = new Vue({ el: '#app', data:{ name:'Wulin biography' }, </script> </html>
List rendering
-
v-for instruction
- Used to display list data
- Syntax: v-for="(item, index) in XXX": key = "YYY"
- Traversable: array, object, string (rarely used), specified number of times (rarely used)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>conditional rendering </title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <!-- Prepare a container --> <div id="app"> <!-- Traversal array --> <ul> <li>xxx-xxx</li> <li>xxx-xxx</li> <li>xxx-xxx</li> <h2>Personnel list</h2> <li>full name-Age</li> <!-- :key="expression"Make every li Nodes are dynamically bound with a unique ID --> <!-- key="1"Generated li Signs are all 1 --> <li v-for="p in persons" :key="p.id"> <!-- Interpolation syntax p It can also be from attributes --> {{p.name}}-{{p.age}} </li> <li v-for="(a,b,c) in persons" :key="p.id"> <!-- The output resolution is item(Each item traversed)---Index value(The number of zeros in the array starts)---undefined --> {{a}---{{b}}---{{c}} <!-- {id:'001',name:'Zhang San',age:18}---0--- --> </li> <li v-for="(p,index) in persons" :key="index"> {{p.name}}-{{p.age}} </li> <li v-for="(p,index) of persons" :key="index"> {{p.name}}-{{p.age}} </li> </ul> <!-- Traversal object --> <h2>Car information</h2> <ul> <li v-for="(value, k) in car" :key="k"> {{value}}-{{k}} </li> <!-- audi A8-name 70 ten thousand-price black-color --> </ul> <!-- Traversal string --> <h2>Test traversal string</h2> <ul> <li v-for="(char, index) in str" :key="index"> {{char}}-{{index}} </li> <!-- h-0 e-1 y-2 --> </ul> <!-- Traverse the specified number of times --> <h2>Test traversal specified times (less used)</h2> <ul> <li v-for="(number, index) in 3" :key="index"> {{number}}-{{index}} </li> <!-- 1-0 2-1 3-2 --> </ul> </div> </body> <script type = "text/javascript"> Vue.config.productionTip = false // Create Vue instance const vm = new Vue({ el: '#app', data:{ persons:[ {id:'001',name:'Zhang San',age:18}, {id:'002',name:'Li Si',age:19}, {id:'003',name:'Wang Wu',age:20} ], car:{ name:'audi A8', price:'70 ten thousand', color:'black' }, str:'hey' }, </script> </html>
key function and principle
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>conditional rendering </title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <!-- Prepare a container --> <div id="app"> <!-- Traversal array --> <h2>Personnel list(Traversal array)</h2> <button @click.once='add'>Add a person</button> <ul> <li v-for="(p,index) of persons" :key="index"> {{p.name}}-{{p.age}} </li> </ul> </div> </body> <script type = "text/javascript"> Vue.config.productionTip = false // Create Vue instance const vm = new Vue({ el: '#app', data:{ persons:[ {id:'001',name:'Zhang San',age:18}, {id:'002',name:'Li Si',age:19}, {id:'003',name:'Wang Wu',age:20} ] }, method:{ add(){ const p = {id:'004',name:'Zhao Liu',age:40} // The array is preceded by an array p this.persons.unshift(p) } } </script> </html>
Function of key when traversing the list (index as key)
The role of the key when traversing the list (the unique id of the data is used as the key)
summary
Interview question: what is the role of the key in react and vue? (internal principle of key)
- 1. Role of key in virtual DOM:
- key is the identification of the virtual DOM object. When the data changes, Vue will generate a new virtual DOM according to the new data. Then Vue will compare the differences between the new virtual Dom and the old virtual dom. The comparison rules are as follows:
- 2. Comparison rules:
- (1). The same key as the new virtual DOM was found in the old virtual DOM:
- ①. If the content in the virtual DOM does not change, directly use the previous real DOM!
- ②. If the content in the virtual DOM changes, a new real DOM is generated, and then the previous real DOM in the page is replaced.
- (2). The same key as the new virtual DOM was not found in the old virtual dom
- Create a new real DOM and then render it to the page.
- (1). The same key as the new virtual DOM was found in the old virtual DOM:
- 3. Possible problems caused by using index as key:
- 1. If the data is added or deleted in reverse order, it will produce unnecessary real DOM updates = = > the interface effect is OK, but the efficiency is low.
- 2. If the structure also contains the DOM of the input class:
- There will be an error DOM update = = > there is a problem with the interface.
- 4. How to select a key during development
- 1. it is best to use the unique identifier of each data as key, such as id, mobile phone number, id card number, student id number and so on.
- 2. If there are no destructive operations such as adding or deleting data in reverse order, it is only used to render the list for display. There is no problem using index as the key.
List filtering
Implementation with monitoring attribute watch
ps: #region #endregion can collapse code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>conditional rendering </title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <!-- Prepare a container --> <div id="app"> <h2>Personnel list</h2> <!-- Collect user input --> <input type="text" placeholder="Please enter your name" v-model="keyWord"/> <ul> <li v-for="(p,index) of filPerons" :key="index"> {{p.name}}-{{p.age}} </li> </ul> </div> </body> <script type = "text/javascript"> Vue.config.productionTip = false // Create Vue instance const vm = new Vue({ el: '#app', data:{ keyWord:'', persons:[ {id:'001',name:'Ma Dongmei',age:18,sex:'female'}, {id:'002',name:'Zhou Dongyu',age:19,sex:'female'}, {id:'003',name:'Jay Chou',age:20,sex:'male'}, {id:'004',name:'Wen zhaolun',age:21,sex:'male'} ], filPerons:[] }, watch:{ // Triggered when the value of the input box changes keyWord:{ immediate:true,//During initialization, let the handler call once, that is: handler('') handler(val){ console.log('keyWord It was changed', val) // Filter data - does not affect the original data, but returns a new array of data // Only by reassigning the new array to persons can it be changed, but the filtered data is really missing // Assign to filPerons and traverse filPerons this.filPerons= this.persons.filter((p)=>{ // Whether indexOf contains a string. If not, return - 1. If yes, return the location (starting from 0) // indexOf('')indexOf an empty string will return 0 instead of - 1 retuen p.name.indexOf(val) !== -1 }) } } } }) </script> </html>
Using computing attribute computer to realize
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>conditional rendering </title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <!-- Prepare a container --> <div id="app"> <h2>Personnel list</h2> <!-- Collect user input --> <input type="text" placeholder="Please enter your name" v-model="keyWord"/> <ul> <li v-for="(p,index) of filPerons" :key="index"> {{p.name}}-{{p.age}} </li> </ul> </div> </body> <script type = "text/javascript"> Vue.config.productionTip = false // Create Vue instance const vm = new Vue({ el: '#app', data:{ keyWord:'', persons:[ {id:'001',name:'Ma Dongmei',age:18,sex:'female'}, {id:'002',name:'Zhou Dongyu',age:19,sex:'female'}, {id:'003',name:'Jay Chou',age:20,sex:'male'}, {id:'004',name:'Wen zhaolun',age:21,sex:'male'} ] }, computed:{ filPerons(){ // The return of the calculated attribute is the result of filPerons return this.persons.filter((p)=>{ // The return value of filter is an array of filtered results retuen p.name.indexOf(this.keyWord) !== -1 }) } } }) </script> </html>
sort list
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>conditional rendering </title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <!-- Prepare a container --> <div id="app"> <h2>Personnel list</h2> <input type="text" placeholder="Please enter your name" v-model="keyWord"/> <button @click="sortType =2">Ascending order of age</button> <button @click="sortType =1>Age descending order</button> <button @click="sortType =0">Original sequence</button> <ul> <li v-for="(p,index) of filPerons" :key="p.id"> {{p.name}}-{{p.age}} </li> </ul> </div> </body> <script type = "text/javascript"> Vue.config.productionTip = false // Create Vue instance const vm = new Vue({ el: '#app', data:{ keyWord:'', sortType:0,//0 original order 1 descending order 2 ascending order //Original data persons:[ {id:'001',name:'Ma Dongmei',age:30,sex:'female'}, {id:'002',name:'Zhou Dongyu',age:18,sex:'female'}, {id:'003',name:'Jay Chou',age:29,sex:'male'}, {id:'004',name:'Wen zhaolun',age:21,sex:'male'} ] }, // As long as any one of the calculated attributes changes, the calculated attributes will be recalculated computed:{ filPerons(){ // Filter result array const arr = this.persons.filter((p)=>{ // The return value of filter is an array of filtered results retuen p.name.indexOf(this.keyWord) !== -1 }) // Determine whether you need to sort // As long as it is not 0 to bool, it is 1 if(this.sortType){ // Sorting will receive two data items, and sort will change the original array // Ascending order: Previous - subsequent; Descending order: last item - first item arr.sort((p1,p2)=>{ return this.sortType === 1? p2.age-p1.age:p1.age-p2.age }) } // Results of filPerons return arr } } }) </script> </html>