Micheal J. Roberts
Micheal J. Roberts

Reputation: 4170

Vue.js - 'v-bind' directives require an attribute value (vue/valid-v-bind)

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?

Upvotes: 2

Views: 2690

Answers (3)

Abhishek Kashyap
Abhishek Kashyap

Reputation: 41

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>

Upvotes: 1

palaѕн
palaѕн

Reputation: 73906

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>

Upvotes: 2

Gabriel Willemann
Gabriel Willemann

Reputation: 1921

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 [].

Upvotes: 5

Related Questions