Stephan-v Stephan-v - 3 months ago 21
JSON Question

Vuejs getting the element that is being called by an event?

I have multiple list items that I want to toggle active classes on when they are being clicked on.

<ul class="list-body">
<li v-on="click: setFilter('style', 'pils')" v-class="active: isActive">Pils</li>
<li>Dubbel</li>
<li>Tripel</li>
<li v-on="click: setFilter('style', 'Quadrupel')">Quadrupel</li>
<li>Wit</li>
</ul>


I already have a
setFilter
click function where I can add extra functionality to activate the class
onClick
.

setFilter: function(facet, value) {
// Facet for style of beer(search filter)
this.helper.addDisjunctiveFacetRefinement(facet, value).search();
},


My question is how can select the specific
li
element that was clicked on and called the with
setFilter
method?

I want to set a variable for the active class
false
or
true
for each single
li
element that has been clicked (or not clicked).

Answer

You can directly pass the event and the events target in your function. The target is the element you clicked on.

HTML:

<ul id="demo">
    <li v-on="click: onClick">Trigger a handler</li>
    <li v-on="click: n++">Trigger an expression</li>
</ul>

JS:

var vue = new Vue({
  el: '#demo',
  data: {},
  methods: {
    onClick: function (e) {
      var clickedElement = e.target;
    }
  }
})

With your element you can do what you want. For example, if you use jQuery:

$(clickedElement).siblings().removeClass('active');
$(clickedElement).addClass('active');
Comments