Documentation 1.0 Help

Class and Style

Now we going to learn how to use class and style in Vue.js.

First, using our previous example, we're going to create a .css file

.color-box { width: 50px; height: 50px; margin-top: 8px; border: 2px solid #d8d8d8; border-radius: 50%; }

Then, import to our HTML file.

<link rel="stylesheet" href="style.css">

Now, we're going to define the class in our HTML file.

<div v-for="variant in variants" :key="variant.id" @mouseover="updateImage(variant.image)" class="color-box" > </div>

Now, we're going to add the style attribute to our div element.

<div v-for="variant in variants" :key="variant.id" @mouseover="updateImage(variant.image)" class="color-box" :style="{ backgroundColor: variant.color }" > </div>

And that's it! Now every variant will have a different color, pre-defined in our variants array.

Another example, is using classes to disable a element.

<button @click="addToCart" :disabled="!inStock" :class="{ disabledButton: !inStock }"> Add to Cart </button>

in here we are using the :disabled attribute to disable the button when the inStock is false.

another example is using the :class attribute to change the class of a object.

<div :class="[isActive ? 'active' : '']"></div>
data() { return { isActive: true } }

in here, we are using the :class attribute to change the class of the div element, when the isActive is true, the class will be active, if not, the class will be empty.

Last modified: 18 janeiro 2024