Vue列表 — 事件委托

前言

做为疯狂的操纵dom转到vue这样经过数据驱动的程序员来讲,姿式的转换也天然产生了不少疑问。
好比,事件委托。
包括我看如今公司的前端代码,发现全部列表的绑定形式都是:前端

<ul>
    <li v-for="(item, index) in data" @click="handleClick(index)">
        Click Me
    </li>
</ul>

而后这样的话,结果就是全部的li元素都绑定了事件。vue

好比下图就是一个失败案例node

clipboard.png

咱们都知道,过多的事件对于性能来讲是很糟糕的,尤为在移动端,能够说是没法容忍。程序员

解决方案

直接上代码:app

<body>
  <div id="app">
    <my-component></my-component>
  </div>
  
  <script src="./vue.js"></script>
  <script>
    let component = {
      template: `
        <ul @click="handleClick">
          <li v-for="(item, index) in data" :data-index="index">
            {{ item.text }}
          </li>
        </ul>
      `,
      data() {
        return {
          data: [
            {
              id: 0,
              text: '0',
            },
            {
              id: 1,
              text: '1',
            },
            {
              id: 2,
              text: '2',
            }
          ]
        }
      },
      methods: {
        handleClick(e) {
          // 多谢 `@微醺岁月` 提醒,要过滤掉ul,否则会出问题
          if (e.target.nodeName.toLowerCase() === 'li') {
            const index = parseInt(e.target.dataset.index)
            // 得到引索后,只须要修改data数据就能改变UI了
            this.doSomething(index)
          }
        },
        doSomething(index) {
          // do what you want
          alert(index)
        }
      }
    }

    new Vue({
      el: '#app',
      components: {
        'my-component': component
      }
    })
  </script>
</body>

经过在li元素中额外加一个data-index就能够实现委托啦~dom

最后,让咱们再看一下结果:性能

clipboard.png

相关文章
相关标签/搜索