Basic Class Binding
Vue allows us to bind classes dynamically using the v-bind
directive. This helps in adding or removing classes based on conditions.
<div class="element" v-bind:class="{ red: isRed }">
This is my element
</div>
In the Vue component, we define isRed
as a reactive state:
import { ref } from 'vue';
export default {
setup() {
const isRed = ref(true);
return { isRed };
}
};
When isRed
is true
, the red
class is applied to the element; otherwise, it is removed.
Applied styles Toggling Classes Dynamically
Now we have only static class so we can add a button that allows us to toggle the red class.
<button @click="isRed = !isRed">Toggle Red Class</button>
Using Objects for Class Binding
<div class="element" v-bind:class="{ red: isRed, large: isLarge }">
Styled Element
</div>
<button @click="isLarge = !isLarge">Toggle Large Class</button>
Instead of binding a single class, we can use an object to manage multiple classes:
Here, isRed
and isLarge
are reactive properties that control the applied classes.
import { ref } from 'vue';
export default {
setup() {
const isRed = ref(false);
const isLarge = ref(false);
return { isRed, isLarge };
}
};
This approach allows multiple styles to be applied dynamically.
Using Arrays for Class Binding
We can also use an array to bind multiple classes dynamically:
<div class="element" v-bind:class="[colors.red, colors.blue]">
Colored Element
</div>
import { ref } from 'vue';
export default {
setup() {
const colors = ref({ red: 'red', blue: 'blue' });
return { colors };
}
};
This method is useful when we want to manage styles dynamically with an array structure.
Inline Styles with Vue
Vue also allows inline styles using v-bind:style
:
<div class="element" v-bind:style="dynamicStyle">
Styled Element
</div>
import { ref } from 'vue';
export default {
setup() {
const dynamicStyle = ref({ fontSize: '20px', color: 'green' });
return { dynamicStyle };
}
};
We can also dynamically update styles:
<button @click="dynamicStyle.fontSize = '40px'">Increase Font Size</button>
This method is useful for modifying styles dynamically without predefined CSS classes.