Dynamic Class in Vue.js
If you can add a dynamic class name to your component it is an ability which is great to have. This will enable us to write custom themes more easily, add classes depending on the state of the component, and write different types of the component which depend on styling. It is simple to add dynamic classes. Just like adding property add :class=”classname” to your component. The classname added to your component will be the classname evaluated to it. Let’s see an example of how to add a dynamic class. Suppose you want to apply the class background-dark to an element only if the isDark prop is true and else add background-light. You should do this by adding :class="[ isDark ? 'background-dark' : 'background-light' ]".
<template>
<div :class="[ isDark ? 'background-dark' : 'background-light' ]">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
props: {
isDark: Boolean
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.background-dark {
background-color: #000;
}
.background-light {
background-color: #fff;
}
</style>
Comments
0 comments
Please Sign in or Create an account to Post Comments