1

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?

1 Answer 1

4

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>

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

2 Comments

Thanks! I tried changing it (adding quotes) but it still doesn't seem to be working...
It must be something else. Check the updated answer, I have added a demo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.