Skip to content
Advertisement

how to add or remove class in vuejs 2 based on id

I want to add or remove class to an element based on id using vuejs, but this code applies the behaviour to all elements. How can I add/remove a class to the element by id? Thanks all in advance.

new Vue({
el:"#test",
data: {
msg: 'msg goes here',
isActive: false
},
  methods: {
    log: function(e) {
    this.isActive =  ! this.isActive
    //alert(e.currentTarget.id);
  }
}
});
.active {
  background: red
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>

<div id="test">

<div id="1" v-on:click="log($event)" v-bind:class="{ active: isActive  }">
{{ msg }}
</div>


<div id="2" v-on:click="log($event)" v-bind:class="{ active: isActive }">
{{ msg }}
</div>


</div>

Advertisement

Answer

Here is an example of using components to achieve the behavior you are looking for:

// register
const clickable = Vue.component('clickable', {
  props: ['msg'],
  data: function() {
    return {
      isActive: false
    }
  },
  template: '<div :class="{ active: isActive }" @click="isActive = !isActive">{{ msg }}</div>'
})

new Vue({
  el: "#test",
  components: {
    clickable
  },
  data: function() {
    return {
      msg: 'msg goes here',
      isActive: false
    }
  }
});
.active {
  background: red
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>

<div id="test">
  
  <clickable :msg='msg'></clickable>
  
  <clickable :msg='msg'></clickable>

</div>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement