实现vue列表的事件委托


使用jq的的事件委托对dom元素的操作是非常方便的vue的事件绑定相当于一级事件的绑定,事件过多的绑定对于浏览器的性能非常的不好。

解决方案

<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<body v-on:keyup.enter="test">
	<div class="" id="vue-template">
		<ul @click="ceshiClick">
			<li v-for="(item, index) in textCeshi" :data-index="index">
				<span>{{ item.text }}</span>
				<span>哈哈哈啊哈哈哈</span><span><button type="button" :data-index="index">ceshi</button></span>
			</li>
		</ul>
		<input>
	</div>
</body>
	<script type="text/javascript">
		var app = new Vue({
			el: '#vue-template',
			data: {
				textCeshi: [{
						id: 0,
						text: '0',
					},
					{
						id: 1,
						text: '1',
					},
					{
						id: 2,
						text: '2',
					}
				]
			},
			methods: {
				ceshiClick(e) {
					console.log(e.target.nodeName.toLowerCase())
					console.log(e.target.dataset.index)
					if (e.target.nodeName.toLowerCase() === 'buttom') {
						const index = parseInt(e.target.dataset.index)
						console.log(index)
					}
					if (e.target.nodeName.toLowerCase() === 'li') {
						const index = parseInt(e.target.dataset.index)
						console.log(index)
					}
				},
			}
		})
	</script>

这种办法在列表中非常有效需要在什么元素上绑定事件直接添加:data-index="index" 然后通过下标去更改data的数据就行了

参考链接(https://segmentfault.com/a/1190000011698763)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM