[Vuejs]-Toggling a class to an element when clicked using 'this'

3👍

Just access the event target from the method itself:

methods: {
    addClassB: function (event) {
        event.target.classList.toggle("classB");
    }
}

So there’s no longer any need to pass any arguments into the handler:

<div class='classA' v-on:click='addClassB'></div>

See proof-of-concept example below:

new Vue({
  el: '#app',
  methods: {
    addClassB(event) {
      event.target.classList.toggle('classB');
    }
  }
});
#app {
  display: flex;
}
#app div {
  width: 50px;
  height: 50px;
  margin: 10px;
}
.classA {
  background: red;
}
.classB {
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="classA" v-on:click="addClassB"></div>
  <div class="classA" v-on:click="addClassB"></div>
  <div class="classA" v-on:click="addClassB"></div>
</div>
👤Terry

0👍

Instead of using this use event.target. From Vue doc – https://v2.vuejs.org/v2/guide/events.html#Method-Event-Handlers:

greet: function (event) {
  // `this` inside methods points to the Vue instance
  alert('Hello ' + this.name + '!')
  // `event` is the native DOM event
  if (event) {
    alert(event.target.tagName)
  }
}

In your code:

methods: {
    addClassB: function (event) {
        event.target.classList.toggle("classB");
    }
}

and:

<div class='classA' v-on:click='addClassB'></div> 

Leave a comment