1. Key function:

The most common use case for accelerating virtual DOM rendering as a uniquely identified node to ensure uniqueness and prevent repeated rendering, resulting in additional performance overhead, is the combination of V-for:

<ul>
  <li v-for="item in items" :key="item.id">.</li>
</ul>
Copy the code

Note: Child elements that have the same parent must have a unique key. Duplicate keys cause render errors. Error message

Whether an error message occurs in the following scenarios:

Example 1: An error message is displayed when the index is used by the same parent

<div class="page">
  <div class="oneSection">
    <el-button
      v-for="(item, index) in displayData"
      size="medium"
      :key="index"
    >{{ item.name }}
    </el-button>
    <el-button
      v-for="(item, index) in displayData"
      size="medium"
      :key="index"
    >{{ item.name }}
    </el-button>
  </div>
</div>
Copy the code


Example 2: No error message is displayed when the same parent uses ID as the key value

<div class="oneSection">
  <el-button
    v-for="item in displayDataOne"
    size="medium"
    :key="item.id"
  >{{ item.name }}
  </el-button>
  <el-button
    v-for="item in displayDataTwo"
   size="medium"
   :key="item.id"
 >{{ item.name }}
 </el-button>
</div>
Copy the code


Example 3: No error message is reported when different parent elements use index

<div class="page">
  <div class="oneSection">
    <el-button
      v-for="(item, index) in itemOne"
      size="medium"
      :key="index"
    >{{ item.name }}
    </el-button>
  </div>
  <div class="twoSection">
    <el-button
      v-for="(item, index) in itemTwo"
      size="medium"
      :key="index"
    >{{ item.name }}
    </el-button>
  </div>
</div>
Copy the code

2. Evading methods under the same parent level

– method

<div>
    <div v-for="(item, i) in itemOne" :key="i"></div>

    <div v-for="(item, i) in itemTwo" :key="'A'+ i"></div>

    <div v-for="(item, i) in itemThree" :key="'B'+ i"></div>
</div>
Copy the code

– the method 2

Use a key that represents the uniqueness of the data, such as id, if the rendered data contains an ID value

<div>
    <div v-for="item in itemOne" :key="item.id"></div>

    <div v-for="item in itemTwo" :key="item.id"></div>

    <div v-for="item in itemThree" :key="item.id"></div>
</div>
Copy the code

Note: the A and B characters can be replaced by any character you define, just to ensure that the key is unique

Why must a unique key be added when using V-for?