Vue_v-for中key的使用注意事项

  • v-for循环的时候,key属性只能使用number获取string
  • key在使用的时候,必须使用v-bind属性绑定的形式,指定key的值,绑定的是循环的那个对象。

代码示例:

<div id="app">
        <label for="id">
            <input type="text" v-model="n1">
        </label>
        <label for="name">
            <input type="text" v-model="n2">
        </label>
        <input type="button" value="push" @click="push">
        <input type="button" value="unshift" @click="unshift">
        <p v-for="person in arrObj" :key="person">
            <input type="checkbox">id:{{person.id}}--name:{{person.name}}
        </p>
    <!--前两个input用v-model双向绑定数据n1,n2,对之后两个button绑定click事件处理程序-->
    <!--对p标签使用v-for循环对象数组,获取到的每一个数组的元素都是对象,它们在写入过程都保存在person之中,此时的person对象只保存当前的数组对象-->
    <!--v-bind绑定key特性为当前的person对象,这样做得到的结果是:选中循环得到的某一个多选框,在执行添加的过程中它被选中的状态不会因为顺序的改变而被改变,因为选中的状态与当前对象是绑定的-->
    </div>
var vm = new Vue({
            el: "#app",
            data: {
                n1: 1,
                n2: 1,
                arrObj: [{
                    id: 1,
                    name:'name1'
                }, {
                    id: 2,
                    name: "name2"
                }, {
                    id: 3,
                    name: "name3"
                }, {
                    id: 4,
                    name: "name4"
                }, {
                    id: 5,
                    name: "name5"
                }, {
                    id: 6,
                    name: "name6"
                }]
            },
            methods: {
                unshift() {
                    this.arrObj.unshift({
                        id: this.n1,
                        name: this.n2
                    });
                },
                push() {
                    this.arrObj.push({
                        id: this.n1,
                        name: this.n2
                    });
                }
            }
        });
原文地址:https://www.cnblogs.com/Syinho/p/12363343.html