Vue loop rendering v-for and v-if, key

 1、v-for和v-if

conventional usage

    <div class="app">
        <div v-for="el in arr">
            <div v-if="el.number>200">
                <h1>{
    
    {el.number}}</h1>
                <h2>{
    
    {el.name}}</h2>
            </div>
        </div>
    </div>
new Vue({
            el: ".app",
            data: {
                arr: [{
						number: 111,
						name: "Bob"
					}, {
						number: 222,
						name: "jack"
					}, {
						number: 333,
						name: "Steven"
					}]
            },
            
               
        }
        )

renderings

The conventional method will cause a problem: v-if will create a div to hold the obtained data every time the judgment is successful, which is equivalent to using two divs to hold the data.

 To solve this problem we can use the ice element <template></template>

    <div class="app">
        <div v-for="el in arr">
            <template v-if="el.number>200">
                    <h1>{
    
    {el.number}}</h1>
                    <h2>{
    
    {el.name}}</h2>
            </template>

        </div>
    </div>

so that we can solve this problem

 2、key

When the number of container data in the for loop in data changes, it will be compared with the number of vm nodes in for. If there are too many data, the corresponding number of nodes will be added behind the vm node, and all nodes will not be recreated, and then vm To update the corresponding DOM and then refresh the data to the interface: Render according to the data order in the for data container. If the user has operated the old node before, the new data order may not match the old node order (the old node Does not correspond to the old data)

For example:

<div id="app">
			<h1>点击按钮</h1>
			<div v-for="el in arr">
				<input type="checkbox" :value="el.id">
				<b>{
    
    {el.title}}</b>
			</div>
			<button @click="addmore">加载更多</button>
		</div>
new Vue({
				el:"#app",
				data:{
				      id:5,
					arr:[{id:1,title:"游泳"},
					{id:2,title:"跑步"},
					{id:3,title:"跳远"},
					{id:4,title:"爱好"}]
				},
				methods:{
					addmore(){
						let obj={id:this.id++,title:"爱好"+this.id}
						// this.arr.push(obj)
						this.arr.unshift(obj)
					}
				}
			})

interface display

When any of the checkbox buttons are selected,

At this time, if you click the load more button, the bug of the check box will appear: the check box button does not follow the movement, and is always at the previous position

In order to solve this problem, the key value is introduced:

      When the for loop uses the data and the created node to bind the unique key value to the element

 So make a slight modification in the previous HTML code such as: <div v-for="el in arr" :key="el.id">

so that it can be bound

 

Guess you like

Origin blog.csdn.net/m0_63470734/article/details/126614090