Sinan
Sinan

Reputation: 5980

Binding events to multiple elements in Vue.js

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

Answers (1)

Roy J
Roy J

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 lis. In the event object, target indicates on which element the event triggered, and currentTargetindicates 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

Related Questions