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

相關文章
相關標籤/搜索