[Vue] basic series list rendering

Posted by christophebmx on Wed, 26 Jan 2022 05:51:53 +0100

1, Basic list

  1. v-for instruction:
    (1) Used to display list data
    (2) Syntax: V-for = "(item, index) in XXX": key = "YYY"
    (3) Traversal: array, object, string (rarely used), specified number of times (rarely used)
    <!-- Traversal array -->
    <li v-for="(p,index) of persons" :key="index">
    	{{p.name}}-{{p.age}}
    </li>
    
    <!-- Traversal object -->
    <li v-for="(value,k) of car" :key="k">
    	{{k}}-{{value}}
    </li>
    
    <!-- Traversal string -->
    <li v-for="(char,index) of str" :key="index">
    	{{char}}-{{index}}
    </li>
    
    <!-- Traverse the specified number of times -->
    <li v-for="(number,index) of 5" :key="index">
    	{{index}}-{{number}}
    </li>
    
  2. What is the role of the key in react and vue? (interview questions):
    • 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, and then Vue will compare the difference between the new virtual Dom and the old virtual dom.
    • Comparison rules: (1) the same key as the new virtual DOM is found in the old virtual DOM: if the content in the virtual DOM does not change, use the previous real DOM directly! 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 is not found in the old virtual dom. Create a new real Dom and then render it to the page.
    • Problems that may be caused by using index as a key: if the data is added or deleted in reverse order, unnecessary real DOM updates will be generated = = > the interface effect is OK, but the efficiency is low. If the structure also contains the dom of the input class, an error will be generated. DOM update = = > there is a problem with the interface.
    • How to select a key during development It is better 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. 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.

2, List operation

  1. List filtering: filter the list according to the search content.
    //Implementation with watch
    new Vue({
    	el:'#root',
    	data:{
    		keyWord:'',         //Design initial search keyword is empty
    		persons:[                    //Search list
    			{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:[]         //Since the original list cannot be overwritten at will, because it will affect the next search, an empty list is prepared to receive the filtered values
    	},
    	watch:{
    		keyWord:{
    			immediate:true,        //It is hoped that all the information can be displayed when searching. Therefore, if the keyword is empty, do a search, and the search results will be all in the list
    			handler(val){
    				this.filPerons = this.persons.filter((p)=>{      //Functions that are not in Vue should use pointer mode as much as possible
    					return p.name.indexOf(val) !== -1         //The syntax rule of indexOf() is: if val is included, the position (0, 1, 2...) will be returned
    				})
    			}
    		}
    	}
    }) 
    //Implemented with computed
    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)=>{    //The information of all matching results is returned
    				return p.name.indexOf(this.keyWord) !== -1   //The returned p is a successful match, which is also a single piece of information
    			})
    		}
    	}
    }) 
    
  2. List sorting: sort the list according to age and other setting information (generally sorting and filtering will appear at the same time)
    computed:{
    	filPerons(){
       //Filtering operation const arr = this.persons.filter((p)=>{ //Save the filtered data to facilitate sorting 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 } }
  3. List of series operations:
    const vm = new Vue({
    	el:'#root',
    	data:{
    		student:{
    			name:'tom',
    			age:18,
    			hobby:['smoking','drink','Hot head'],
    			friends:[
    				{name:'jerry',age:35},
    				{name:'tony',age:36}
    			]
    		}
    	},
    	methods: {  
    		addSex(){                                                       //To add a gender attribute, there are two ways to add it
    			// Vue.set(this.student,'sex', 'male')
    			this.$set(this.student,'sex','male')
    		},
    		addFriend(){
    			this.student.friends.unshift({name:'jack',age:70})      //Add friend info
    		},
    		updateFirstFriendName(){
    			this.student.friends[0].name = 'Zhang San'                    //Modify friend name
    		},
    		addHobby(){
    			this.student.hobby.push('study')                          //Add a hobby
    		},
    		updateHobby(){
    			// this. student. hobby. Spice (0,1, 'driving') / / there are three ways to change your hobby
    			// Vue.set(this.student.hobby,0, 'drive')
    			this.$set(this.student.hobby,0,'drive a car')
    		},
    		removeSmoke(){
    			this.student.hobby = this.student.hobby.filter((h)=>{      //Filter hobbies
    				return h !== 'smoking'
    			})
    		}
    	}
    })
    

3, Vue data monitoring principle

  1. vue will monitor all levels of data in data.
  2. How do I monitor data in objects? Monitoring is realized through setter, and the data to be monitored is passed in when new Vue is created.
    (1) Object, Vue does not respond by default (2) To make a response to the attribute added later, please use the following API:
    • Vue.set(target,propertyName/index,value)
    • vm.$set(target,propertyName/index,value)
  3. How do I monitor data in an array? By wrapping the update elements of the array, the essence is to do two things: (1) call the native corresponding method to update the array. (2) Re parse the template to update the page.
  4. When modifying an element in the Vue array, you must use the following methods: (1) use these APIs: push(), pop(), shift(), unshift(), splice(), sort(), reverse() (2)Vue.set() or VM$ set()
    Special note: Vue Set() and vm$ Set() cannot add attribute to vm or vm's root data object!!!