Rennnn
Rennnn

Reputation: 85

Vuejs v-bind class not applying the classes dynamically

<button @click="startEffect"> Start Effect</button>
<br/>
<div id="effect" class="highlight" :class="{highlight: enableHighlight}"></div>

I just need the highlight class to be applied based on the data property enableHighlight but for some reason It doesn't apply the class when the startEffect function is called.

<script>
    export default {
        data() {
            return {
                enableHighlight: false
            }
        },
        methods: {
            startEffect: function () {
                this.enableHighlight = !this.enableHighlight;
            }
        }
    }
</script>

I have debugged and confirmed that value of enableHighlight is switched when clicking the button and that the CSS classes are present. However upon clicking the button the class is not applied to the div.

Upvotes: 1

Views: 2248

Answers (1)

sandrooco
sandrooco

Reputation: 8716

You really mess with Vue when having a "normal" class attribute and one dynamic. Remove the normal one. <div id="effect" :class="{highlight: enableHighlight}"></div>

To make it work, you need to remove the function in startEffect's definition:

startEffect() {
    this.enableHighlight = !this.enableHighlight;
}

Why? because this isn't the same in the different ways to define the function. Learn more about this here.

Upvotes: 2

Related Questions