Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mikoo's avatar
Level 1

How do I add a class when the button is clicked?

Hi guys, I have a problem. Im new to Vue and I want to apply a class to a button when the button is clicked. In jQuery I would just select the element and add the class but I dont understand how its done in vue. I have the following code:

<div id="vue-instance">
  <span>{{ message }}</span>
  <ol>
    <li v-for="x in items">
      {{ x.title }}
    </li>
  </ol>
  
  <button v-on:click="makeRed" v-bind:class="'red'">
  Click Me
  </button>
</div>
var vm = new Vue({
  el: '#vue-instance',
  data: {
    message: 'Hello',
    items: [
        {title: 'Item 1'},
      {title: 'Item 2'},
      {title: 'Item 3 ' + new Date() }
    ]
  },
  methods: {
    makeRed: function() {
    
    }
  }
});
.red
{
  border: 1px solid red;
  background-color: pink;
}
0 likes
5 replies
tisuchi's avatar

Why not just use jQuery to solve this issue-

<button v-on:click="makeRed" id="mybutton">

and in your method,

makeRed: function() {
    $( "#mybutton" ).addClass( ".red" );    
}

tykus's avatar

Do it is a data-centric way by adding a boolean property to your component with you update whenever the button is clicked

<div id="vue-instance">
    <span>{{ message }}</span>
    <ol>
        <li v-for="x in items">
            {{ x.title }}
        </li>
    </ol>
  
    <button v-on:click="makeRed" :class="{'red': isRed}">
        Click Me
    </button>
</div>
var vm = new Vue({
    el: '#vue-instance',
    data: {
        message: 'Hello',
        isRed: false,
        items: [
            {title: 'Item 1'},
            {title: 'Item 2'},
            {title: 'Item 3 ' + new Date() }
        ]
    },
    methods: {
            makeRed: function() {
                this.isRed = true;
        }
    }
});

Vue will apply the red class whenever isRed evaluated to true.

mikoo's avatar
mikoo
OP
Best Answer
Level 1

Hi guys. I found a way, but I think im gonna stick to jQuery in this situation.

<div id="vue-instance">
  <span>{{ message }}</span>
  <ol>
    <li v-for="x in items">
      {{ x.title }}
    </li>
  </ol>
  
  <button v-on:click="makeRed" v-bind:class="{red: isActive}">
  Click Me
  </button>
</div>
var vm = new Vue({
  el: '#vue-instance',
  data: {
    isActive: false,
    message: 'Hello',
    items: [
        {title: 'Item 1'},
      {title: 'Item 2'},
      {title: 'Item 3 ' + new Date() }
    ]
  },
  methods: {
    makeRed: function() {
        this.isActive = !this.isActive;
    }
  }
});

Please or to participate in this conversation.