Skip to content Skip to sidebar Skip to footer

Vue Bind Click That Adds Active Class (and Removes From The Last One)

I have a v-for loop that adds a section of divs to the page. On page load, the first one should be selected and then when you click another one, it should add the active class to t

Solution 1:

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):

newVue({
  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/

Post a Comment for "Vue Bind Click That Adds Active Class (and Removes From The Last One)"