Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS2 - bind part of the class name

Tags:

vue.js

vuejs2

Is it possible to change (bind dynamically) just a part of the class name. For example I have this alert box:

<div class="alert alert-success alert-dismissible">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        <h4><i class="icon fa fa-check"></i> Alert!</h4>
        Success alert preview. This alert is dismissable.
    </div>

This only part of the class which is dynamic is the alert-success class - the success of the class name can be danger, info... (depends on the type of message).

Is it possible to do this?

like image 961
Sasha Avatar asked Nov 24 '25 06:11

Sasha


1 Answers

You can use regular v-bind:

<div :class="'alert alert-' + classType + 'alert-dismissible'">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
    <h4><i class="icon fa fa-check"></i> Alert!</h4>
    Success alert preview. This alert is dismissable.
</div>

Being classType the property (you can name however you want it). By "property" I mean it can be a data, a computed or even a method call.

Notice the argument to :class is a JavaScript expression:

'alert alert-' + classType + 'alert-dismissible'

So mind the quotes.

You can also use array syntax, if you find it clearer:

<div :class="['alert', 'alert-' + classType, 'alert-dismissible']">

As reminded by @Sphinx in the comments, you can also use both bound (:class) and unbound (class) attributes at the same time, Vue will merge them appropriately:

<!-- if classType equals to the whole class name, like 'alert-active' -->
<div class="alert alert-dismissible" :class="classType">
<!-- if classType equals to just a part of class name, like 'active' -->
<div class="alert alert-dismissible" :class="'alert-' + classType">
like image 160
acdcjunior Avatar answered Nov 28 '25 16:11

acdcjunior