Skip to content
Advertisement

Vue.js bind to a class according to a condition

With this div declaration:

<div v-bind:class="[currentPage === 'help' ? highlight : '']">

that I build accordingly to: https://v2.vuejs.org/v2/guide/class-and-style.html#Array-Syntax

But the binding isn’t working (the class ‘highlight’ never applied regardless of the currentPage value).

I have this model where there is the currentPage variable keeping track of the active page:

    var vueApp = new Vue({
        el: '#vueApp',
        data: {
            currentPage: 'help',

How can I activate the binding of a class on an element, based on the string value of a vue property?

Advertisement

Answer

In the template:

<div v-bind:class="[currentPage === 'help' ? highlight : '']">

highlight is an identifier.

Thus, such expression expects that highlight is property of the Vue instance/component. It is being evaluated, but since it probably is empty (undefined) you get nothing.

Since you want the string, do:

<div v-bind:class="[currentPage === 'help' ? 'highlight' : '']">

Demo:

new Vue({
  el: '#vueApp',
  data: {
    currentPage: 'help',
  }
})
.highlight { background-color: yellow }
<script src="https://unpkg.com/vue"></script>

<div id="vueApp">
  <div v-bind:class="[currentPage === 'help' ? 'highlight' : '']">Hello</div>
</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement