class name based on string in variables in vue.js

5.4k views Asked by At

I want to add a dynamic and a static class to an element. The following code doesn't work.

var string = 'hugo';

<div v-bind:class="{ staticClass: true, dynamicClass: string }">
    {{ string }}
</div>

This is the expected output I would like to accomplish.

<div class="staticClass hugo">hugo</div>

What I get instead is the following

<div class="staticClass dynamicClass">hugo</div>

Thank you very much in advance.

2

There are 2 answers

0
Jns On BEST ANSWER

As referenced here you can pass an array to v-bind:class to apply multiple classes to your div. Because you have one dynamic class, it would make sense to use the object syntax inside array syntax.

In your case it would be something like that

<div v-bind:class="[{staticClass: true}, string]">
    {{ string }}
</div>

Fiddle

0
SayeMarg On

There is more than one way to do this:

  1. Use an array for dynamic class binding:
<div :class="['staticClass', dynamicClass]">
    {{ string }}
</div>
  1. Use an object and a JavaScript dynamic property name (you ccan create a method that returns this object and bind to it for convenience) :
<div :class="{
    'staticClass': true,
    [dynamicClass]: true
}">
    {{ string }}
</div>
  1. But the best way, in my opinion, is to combine a static class property and a Vue dynamic binding. The dynamic binding (:class) can contain an array, object, a string, or a variable referring to one of the three:
<div class="staticClass" :class="dynamicClass">
    {{ string }}
</div>

See Vue 3 Documentation or This Article.