0

I'm using VueJS 2.3.0, and now I need to update HTML element's class after it's clicked.

I have this template code:

<template id="model-template">
    <span>
        <button v-on:click="activate" >{{ model.fu }} month</button>
    </span>
</template>

I just checked the VueJS official documentation about :class solution, but I'm confused...

If I use jQuery, then I code this to do what I want to do:

$('button').each(function() {
    $(this).click(function() {
        $('button').removeClass('clicked');
        $(this).addClass('clicked');
    });
});

UPDATE: this is find all buttons, remove 'clicked' class from each button elements, and add 'clicked' class to only that one what the user is clicked.

How can I do same thing in VueJS?

2
  • You want to remove the clicked class from all other buttons in your component and then add it to the button that was clicked? Commented Jun 18, 2017 at 15:40
  • @BertEvans: yes, exactly. Commented Jun 18, 2017 at 16:26

1 Answer 1

1

activeClass is a property in your vue instance.The below syntax means the presence of the active class will be determined by the truthiness of the data property activeClass. i.e if activeClass = true then class active will be added and if activeClass = false it will be removed from the button.

<template id="model-template">
    <span>
        <button v-bind:class="{active : activeClass}" >{{ model.fu }} month</button>
    </span>
</template>

Once you understand and implement it will be even more simple then jquery.

jsfiddle if you want to see it in action: https://jsfiddle.net/riazxrazor/5jfnwav4/4/

Sign up to request clarification or add additional context in comments.

2 Comments

Looking good, but this solution set true / false only that one copy of button element. I want to set all of buttons to false, and only that one true what the user clicked.
i wasn't able to achieve in a simple way had to hack a little but i managed to do it, u can have a look. jsfiddle.net/riazxrazor/5jfnwav4/7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.