Vue - v-for use in the key attribute

When using the v-for in the components, Key is now necessary.

 

First, in order to facilitate the presentation. Let's build an infrastructure

 

 

 

Now we are adding the push method is used, added to the end of the object

Before adding selected fifth and then add the above does not appear abnormal

 

Next we look at if you are using unshift method is added to the front of the object

 

We can see that if before adding the selected one, and then add the phenomenon will appear misplaced index

 

 

So we need to give each and every one of the objects inside the bindings on a unique identifier

This time we can use this key up

 

 After binding us look good

Before you can now see that we do not add new users, we selected the No. 5 or No. 5 after adding selected

Attach the complete code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <div>
            <label>Id:
                <input type="text" v-model='id'>
            </label>

            <label>Name:
                <input type="text" v-model='name'>
            </label>

            <input type="button" value="添加" @click='add'>
        </div>

        <p v-for='item in list' v-bind:key='item.id'>
            <input type="checkbox">{{ item.id }} --- {{ item.name }}
        </p>
    </div>
    <script src="../vue/vue.js"></script>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                id: '',
                name: '',
                list: [{
                    id: 1,
                    name: '勒布朗'
                }, {
                    id: 2,
                    name: 'Durant' 
                }, { 
                    ID: . 3 , 
                    name: 'library' 
                }, { 
                    ID: . 4 , 
                    name: 'Rose' 
                }, { 
                    ID: . 5 , 
                    name: 'George' 
                }] 
            }, 
            Methods: { 
                the Add () { 
                    the this .list.unshift ({ID: the this .id, name: the this .name}) 
                } 
            } 
        })
     </ Script> 
</ body>

</html>

 

Guess you like

Origin www.cnblogs.com/yangpeixian/p/11707069.html