如何在vue项目中给ul>li列表使用事件委托

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

然后这样的话,结果就是所有的li元素都绑定了事件。

我们都知道,过多的事件对于性能来说是很糟糕的,尤其在移动端,可以说是无法容忍。为了更好的解决这个性能问题,我们在这里要引入一个事件委托(又叫事件代理)的概念。即子不教父子过,子债父偿......

我们可以通过在li元素中额外加一个data-index就可以实现委托啦~

<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>

 

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值