Reputation: 5980
Is it possible to bind events to multiple elements in HTML without using components.
Ex:
<ul>
<li>
<li>
<li>
<li>
</ul>
So can I bind a click events to all those <li>
elements. If yes, how?
Upvotes: 1
Views: 3362
Reputation: 43899
You can use event delegation. Since events bubble up, you can put a click handler on the ul
element and it will fire for a click on any of the contained li
s. In the event
object, target
indicates on which element the event triggered, and currentTarget
indicates the element the handler is attached to.
new Vue({
el: 'body',
methods: {
something: function(event) {
console.log('Clicked:', event.target.textContent);
console.log('Binding is on:', event.currentTarget);
}
}
});
ul {
cursor: pointer;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<ul @click="something">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
Upvotes: 6