2

I'm currently attempting to bind classes to an element in the following way:

v-bind:class="{
    `bg-${activeTheme.name}-500 text-white`: styleFilter.active,
    `bg-${activeTheme.name}-400 text-black`: !styleFilter.active,
}"

However, I am receiving the following errors:

Parsing error: Line 2: Unexpected token and 'v-bind' directives require an attribute value (vue/valid-v-bind).

What have I done wrong here?

3 Answers 3

5

Try something like that:

<div
  :class="{
    [`bg-${activeTheme.name}-500 text-white`]: styleFilter.active,
    [`bg-${activeTheme.name}-400 text-black`]: !styleFilter.active,
  }"
>
  teste
</div>

Because if the name of property is dynamic, it's must be declared with [].

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

Comments

2

For dynamic class names, we simply need to use brackets [] around the class names like:

new Vue({
  el: "#myApp",
  data: {
    activeTheme: {
      name: ''
    },
    styleFilter: {
      active: false
    },
  }
})
.text-black { font-size:2em; color: skyblue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="myApp">
  <div v-bind:class="{
      [`bg-${activeTheme.name}-500 text-white`]: styleFilter.active,
      [`bg-${activeTheme.name}-400 text-black`]: !styleFilter.active,
  }">
    Hello World
  </div>
</div>

Comments

1

When you use v-bind you bind it to javascript expression.

To conditionally render class you can do:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<style>
.class-red {
  color: red
}

.class-teal {
  color: teal
}
</style>

<div id="app">
  <h1 v-bind:class="[isActive ? 'class-teal' : 'class-red']">Dynamic class</h1>
  <button @click="[isActive = !isActive]">Switch class</button>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    isActive: true
  }
})
</script>

Comments

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.