1

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 Answers 2

4

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

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

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.