1, v-for
<li v-for="item in items">{{item.name}}</li>
List rendering v-for A set of values can be rendered in a list. The syntax form is: item in items, items Is an array of source data and item Is an alias for an array element iteration. stay v-for Block, full access to the parent scope attribute. v-for It also supports an optional second parameter, which is the index of the current item. v-for You can also traverse the object and specify three formal parameters: form: v-for="(value, key, index) in object" value: The value of the object key: Object's key index: Traversal index
2, key attribute (very important)
When rendering a list with v-for, use the key attribute to assign a unique ID to each
The next time the data is rendered, increase the rendering speed.
<li v-for="item in items" :key="item.id">{{item.name}}</li>
Note: in v-for: key is very important. It is recommended to write: key every time
give an example:
give an example:
By default, there are three labels with values. The effect of a button is to add a row of labels at the top. At this time, problems are easy to occur
Before clicking the button:
After clicking the button:
Result: out of order? The detailed reasons are shown in the figure below. If the comparison is the same, it will be reused, and if the comparison is different, it will regenerate the DOM
Note 1: when: key is not written by default, array index will be added automatically when parsing DOM
Note 2:: key is better to bind the unique id of the data, such as id card, mobile phone number, library table id, etc., so that no matter where the array is inserted, even at the beginning or end of the array, the structure will not be affected.
Note 3: the virtual DOM exists in memory, while the page tags operated by the user belong to the real dom
3, Value range
v-for can also specify an integer to reuse the template multiple times.
< Li V-for = "i in 5" > the {{i}} th time</li>
4, List filtering
For example: filter the content of li tag. Filter the content according to the user's input. It is required to implement it in two ways: calculated and watch
give an example:
Filter the < li > content. Filter the content according to the user's input. It is required to implement it in two ways: computed and watch
Note 1: list filtering is used filter(), which is not the same thing as a custom filter.
List filter filter() is used in methods, while custom filters are used in interpolation expressions and v-bind expressions.
Note 2: The filter will generate new data and will not modify the original data structure.
Note 3: if both calculated and watch methods can be implemented, it is recommended to use the calculated attribute first
Method 1: computed
<div id="root"> <h2>Personnel list</h2> <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}}-{{p.sex}} </li> </ul> </div> new Vue({ el:'#root', data:{ keyWord:'', persons:[ {id:'001',name:'Ma Dongmei',age:19,sex:'female'}, {id:'002',name:'Zhou Dongyu',age:20,sex:'female'}, {id:'003',name:'Jay Chou',age:21,sex:'male'}, {id:'004',name:'Wen zhaolun',age:22,sex:'male'} ] }, computed:{ filPerons(){ return this.persons.filter((p)=>{ return p.name.indexOf(this.keyWord) !== -1 }) } } })
Mode 2: watch
new Vue({ el:'#root', data:{ keyWord:'', persons:[ {id:'001',name:'Ma Dongmei',age:19,sex:'female'}, {id:'002',name:'Zhou Dongyu',age:20,sex:'female'}, {id:'003',name:'Jay Chou',age:21,sex:'male'}, {id:'004',name:'Wen zhaolun',age:22,sex:'male'} ], filPerons:[] }, watch:{ keyWord:{ immediate:true, handler(val){ this.filPerons = this.persons.filter((p)=>{ return p.name.indexOf(val) !== -1 }) } } } })
5, List sorting
Note 1: list sorting is used sort() method, in which sort (parameter 1, parameter 2) has two parameters. Parameter 2 - parameter 1 is in descending order, and parameter 1 - parameter 2 is in ascending order. See details.
Array sort() method
Note 2: it will cause changes in its own data.
Example: perform ascending and descending sequence on the data filtered from the list
Note 3: The sort() method will change the original data structure, such as the order of the original array
<div id="root"> <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}}-{{p.sex}} <input type="text"> </li> </ul> </div> new Vue({ el:'#root', data:{ keyWord:'', sortType:0, //0 original order 1 descending order 2 ascending order persons:[ {id:'001',name:'Ma Dongmei',age:30,sex:'female'}, {id:'002',name:'Zhou Dongyu',age:31,sex:'female'}, {id:'003',name:'Jay Chou',age:18,sex:'male'}, {id:'004',name:'Wen zhaolun',age:19,sex:'male'} ] }, computed:{ filPerons(){ const arr = this.persons.filter((p)=>{ return p.name.indexOf(this.keyWord) !== -1 }) //Determine whether you need to sort if(this.sortType){ arr.sort((p1,p2)=>{ return this.sortType === 1 ? p2.age-p1.age : p1.age-p2.age }) } return arr } } })
6, How Vue monitors "object" data changes
Note 1: the principle of vue monitoring data is to add get() and set() methods to each data attribute, that is, data attribute change = "call set() =" re render page value change.
Note 2: loading process:
1) Load the data attribute and process and encapsulate the get() and set() methods
2)vue._data=data, so that the console can see a pile of attributes and methods by clicking Vue instance
For example: when the attribute value of the simulated data object changes, the page value also changes, that is, to achieve the effect of vue monitoring data change
For example: when the attribute value of the simulated data object changes, the page value also changes, that is, to achieve the effect of vue monitoring data change
let data = { name:'Shang Silicon Valley', address:'Beijing', } //Step 1: create a monitored instance object to monitor the changes of attributes in data const obs = new Observer(data) console.log(obs) //Step 2: prepare a vm instance object let vm = {} vm._data = data = obs //Step 3: define the observer function function Observer(obj){ //Summarize all the attributes in the object to form an array const keys = Object.keys(obj) //ergodic keys.forEach((k)=>{ Object.defineProperty(this,k,{ //this refers to the observer object, not the vue instance get(){ return obj[k] }, set(val){ console.log(`${k}It's changed. I'm going to parse the template and generate virtual DOM.....I'm going to get busy`) obj[k] = val } }) }) }
7, Vue Set () or VM$ Set() dynamically add labels
Vue.set() and VM$ Set() = "same effect.
Mainly explain Vue What is the set () method?
Note 1: vue The set () method has limitations. It cannot be added to the vue instance or the direct attribute of data. It can only act on an attribute object under data.
For example, dynamically adding "principal attribute", that is, dynamically adding "principal attribute" to the school object under the data attribute
For example, dynamically adding "principal attribute", that is, dynamically adding "principal attribute" to the school object under the data attribute
<body> <!-- Prepare a container--> <div id="root"> <h1>School information</h1> <h2>School Name:{{school.name}}</h2> <h2>School address:{{school.address}}</h2> <h2>The principal is:{{school.leader}}</h2> <hr/> <h1>Student information</h1> <button @click="addSex">Add a gender attribute. The default value is male</button> <h2>full name:{{student.name}}</h2> <h2 v-if="student.sex">Gender:{{student.sex}}</h2> <h2>Age: real{{student.age.rAge}},foreign{{student.age.sAge}}</h2> <h2>Friends</h2> <ul> <li v-for="(f,index) in student.friends" :key="index"> {{f.name}}--{{f.age}} </li> </ul> </div> </body> <script type="text/javascript"> Vue.config.productionTip = false //Prevent vue from generating production prompts at startup. const vm = new Vue({ el:'#root', data:{ school:{ name:'Shang Silicon Valley', address:'Beijing', }, student:{ name:'tom', age:{ rAge:40, sAge:29, }, friends:[ {name:'jerry',age:35}, {name:'tony',age:36} ] } }, methods: { addSex(){ // Vue.set(this.student,'sex', 'male') this.$set(this.student,'sex','male') } } }) </script>
8, How Vue monitors "array" data changes
Question: vue instance object does not provide similar get and set methods for array elements. Why does it realize page responsive listening?
Question 1: vue instance object does not provide similar get and set methods for array elements. Why does it realize page responsive listening?
Answer: because vue encapsulates part of the basic methods of the array, it updates the DOM responsively while inheriting the use effect of the methods.
Example: Hobby list
Example: Hobby list
<div id="root"> <h2>hobby</h2> <ul> <li v-for="(h,index) in student.hobby" :key="index"> {{h}} </li> </ul> </div> const vm = new Vue({ el:'#root', data:{ student:{ hobby:['smoking','drink','Hot head'] } } })
9, Summarize vue data monitoring
Question: what is data hijacking?
Question: what is data hijacking?
Definition: refers to intercepting this behavior through a piece of code, performing additional operations or modifying the returned results when accessing or modifying a property of an object. For example: intercept data attributes and add additional get and set methods to vue instances_ Data object.
Links to other related articles
5.vue2 basic component communication case exercise: todo list case exercise
6.Rewrite todo list case to cache cost
7.vue2 knowledge points: calculation attributes and listening attributes