Notes on key attribute in v-for loop of Vue

Posted by hansman on Fri, 03 Jan 2020 19:44:48 +0100

When Vue is updating the rendered element list with v-for, it defaults to the in place reuse policy. If the order of data items is changed, Vue will not move DOM elements to match the change of data items, but simply reuse each element here, and ensure that it displays each element that has been rendered under a specific index.

In order to give Vue a hint that it can track the identity of each node to reuse and reorder existing elements, you need to provide a unique key attribute for each item. The key attribute can only be of type string or number.

In the following example, if I don't bind the key to the p element, I will first select the first one,

Then enter the ID and Name, click the Add button, and the following situation will appear. The newly added element is selected. This does not happen if the key attribute is bound.

Complete code:

<html>
  <head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>
<body>
  <div id='app'>
    <!--v-for Loop normal array-->
    <div>
      <label>ID:<input type="text" v-model="id"></label>
      <label>Name:<input type="text" v-model="name"></label>
      <input type="button" value="Add to" @click="add" />
    </div>
    <!--Be careful: v-for In the cycle, key Property can only be used number or string -->
    <!--Be careful: key When using, it must be used v-bind Form of binding property, specifying key Value  -->
    <!-- In components, use v-for When circulating, or in some special cases, if v-for Something the matter,
      //You must specify a unique string / number type when using v-for: key value -- >
    <p v-for="item in list" :key="item.id">
      <input type="checkbox"/>
      {{item.id}}--{{item.name}}
    </p>
    
  </div>
</body>
<script src="vue.min.js"></script>
<script>
  var vm = new Vue({
    el:'#app',
    data:{
      id:"",
      name:"",
      list:[
        {id:1, name:'Liz'},
        {id:2, name:'Ying Zheng'},
        {id:3, name:'eunuch who conspired with Li Si to influence the succession to the First Emperor'},
        {id:4, name:'Han Fei'},
        {id:5, name:'a pre-Qin philosopher'},
      ],
    },
    methods:{
      add(){
        this.list.unshift({id:this.id,name:this.name});
      }
    }
  });
</script>
</html>

 

Topics: Vue Attribute