饮水思源:https://www.bilibili.com/video/BV1Zy4y1K7SH?p=30&spm_id_from=pageDriver

一、关于key

反例

一个反例,用index作为key出bug

Vue.js列表渲染&关于列表元素的key&列表过滤与排序

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title></title>
  <script src="JS/vue.js"></script>
</head>

<body>
  <div id="root">
    <h1>{{header}}</h1>
    <ul>
      <!-- 
        key相当于人类的身份证,保证每条数据的key不同就行 。
        1 key只存在于虚拟DOM中
        2 由于虚拟DOM对比算法,采用index作为key时,如果在开头
          或者中间等地方插入,或者其它一些破坏顺序的操作,可能导致,例如
          key=1对应数据实质上已经替换了(不是同一个人了),言下之意,
          1这个身份证号对应的人突然换了一个,虚拟DOM实际上根据key=1去对
          比两个不同的人来对页面进行更新(错位对比),那么不仅可能造成效率问题,
          也可能导致一些出乎意料的其它问题。结论,尽量不用index做id
      -->

      <li v-for="(article, index) in articles" :key="index">
        {{article.title}} --- index = {{index}}
        <input type="text">
      </li>
    </ul>

    <button id="btnAdd">添加一篇文章</button>
  </div>

  <script>
    const articles = [
      {
        id: 1,
        title: '这个是文章1'
      },
      {
        id: 2,
        title: '这个是文章2'
      },
      {
        id: 3,
        title: '这个是文章3'
      },
    ]

    const vm = new Vue({
      el: "#root",
      data: {
        header: "key 的原理探究 --- 一个出错的例子",
        articles: articles,
      },
    })

    let i = 4;
    document.querySelector("#btnAdd").addEventListener("click", () => {
      articles.unshift({
        id: i,
        title: `这个是文章${i++}`,
      })
    })
  </script>
</body>

正例

修改一下,一个正确的例子,用唯一的id作key:

Vue.js列表渲染&关于列表元素的key&列表过滤与排序

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title></title>
  <script src="JS/vue.js"></script>
</head>

<body>
  <div id="root">
    <h1>{{header}}</h1>
    <ul>
      <li v-for="(article, index) in articles" :key="article.id">
        {{article.title}} --- index = {{index}}
        <input type="text">
      </li>
    </ul>

    <button id="btnAdd">添加一篇文章</button>
  </div>

  <script>
    const articles = [
      {
        id: 1,
        title: '这个是文章1'
      },
      {
        id: 2,
        title: '这个是文章2'
      },
      {
        id: 3,
        title: '这个是文章3'
      },
    ]

    const vm = new Vue({
      el: "#root",
      data: {
        header: "key 的原理探究 --- 一个正确的例子",
        articles: articles,
      },
    })

    let i = 4;
    document.querySelector("#btnAdd").addEventListener("click", () => {
      articles.unshift({
        id: i,
        title: `这个是文章${i++}`,
      })
    })
  </script>
</body>
</html>
View Code

相关文章:

  • 2021-12-16
  • 2021-11-19
  • 2021-12-16
  • 2021-11-01
  • 2022-12-23
猜你喜欢
  • 2021-09-26
  • 2021-07-27
  • 2022-12-23
  • 2021-12-15
  • 2021-12-27
  • 2022-12-23
  • 2021-07-23
相关资源
相似解决方案