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