[Vuejs]-Vue bind click that adds active class (and removes from the last one)

2๐Ÿ‘

โœ…

I suggest the following:

if you need only one section be active at a time, create a data property isActive and store current active index there. Also pass current index to changeActive method and store index or clear it if you click an active section again (to toggle class on second click):

new Vue({
  el: '#app',
  data: {
    areaSections: [...],
    isActive: null
  },
  methods: {
    changeActive(index) {
      this.isActive = this.isActive === index ?  null : index
    }
  }
})

Then, in your template, make sure to pass index into click listener:

<section class="monitoring-areas section" v-on:click="changeActive(index)"> 

In the end, bind active class using new data prop:

v-bind:class="{ active: index == isActive }"

Full example can be found here: https://jsfiddle.net/wostex/63t082p2/73/

๐Ÿ‘คEgor Stambakio

Leave a comment