[Vuejs]-How can I inject css class in Vuejs component with javascript?

3👍

The official docs for Class and Style Bindings/Binding HTML Classes show several ways. Below are the most common and some useful demos.

Object Syntax

We can pass an object to v-bind:class to dynamically toggle classes:

<div v-bind:class="{ active: isActive }"></div>

The above syntax means the presence of the active class will be
determined by the truthiness of the data property isActive.

See demo below:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    isActive: true
  }
})
.active { background: yellow; }
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <div v-bind:class="{ active: isActive }">My DIV</div>
  <button @click="isActive = !isActive">activate/deactivate</button>
</div>

Multiple classes

You can have multiple classes toggled by having more fields in the
object. In addition, the v-bind:class directive can also co-exist with
the plain class attribute. So given the following template:

<div class="static"
     v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>

Demo:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    isActive: true,
    hasError: false
  }
})
.active { background: yellow }
.text-danger { color: red; font-weight: bold; }
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <div v-bind:class="{ active: isActive, 'text-danger': hasError }">My DIV</div>
  <button @click="isActive = !isActive">toggle isActive</button>
  <button @click="hasError= !hasError">toggle hasError</button>
</div>

Array Syntax

We can pass an array to v-bind:class to apply a list of classes:

<div v-bind:class="[activeClass, errorClass]"></div>
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

And, of course, you can change that data and the HTML will react. Another demo:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})
.active { background: green }
.inactive { background: yellow }
.text-danger { color: red; font-weight: bold; }
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <div v-bind:class="[activeClass, errorClass]">My DIV</div>
  <button @click="activeClass = 'inactive'">activeClass to inactive</button>
  <button @click="activeClass = 'active'">activeClass to active</button>
</div>

Leave a comment