Vue --事件委托

前端代码

简述:
if(event.target.title == “edit”){ //如果点击到了edit
let id = evenr.target.dataset.id;
//拿着id参数执行着相关的操作
}
利用target获取相关参数传递给一个方法进行执行
好像和后端的有点区别,不是很懂先记下了

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

然后这样的话,结果就是所有的li元素都绑定了事件。
过多的事件对于性能来说是很糟糕的,可以说是无法容忍。

<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
  }
})
通过在li元素中额外加一个data-index就可以实现委托啦~
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值