samuel toh
samuel toh

Reputation: 7086

How to add class on vue.js 2?

My component is like this :

<template>
    <span class="rating">
        ...
    </span>
</template>
<script>
    export default{
        props: {
            'star': null
        }, 
        created: function() {
            if(this.star != null)
                $(".rating").addClass('test');
        }
    }
</script>

When the page reload first, I want to check prop star. If the prop star not equal to null, then add class test

I try like my code above, but it does not work

Is there anyone who can help me?

Upvotes: 0

Views: 4559

Answers (1)

Amresh Venugopal
Amresh Venugopal

Reputation: 9549

You don't need to use jQuery for that.

<template>
    <span :class='{"rating": star !== null}'>
        ...
    </span>
</template>
<script>
    export default{
        props: {
            'star': null
        }
    }
</script>

:class is property binding syntax, you can say that it is now able to access the variables in your vue-component.

{'rating': star !== null} this simple boolean expression will ensure if .rating has to be added or not.

You can also do something like:

:class='{"rating": !!star}'

If the expression evaluates to a truthy, you will get the class applied.

Upvotes: 5

Related Questions