25
loading...
This website collects cookies to deliver better user experience
While we can certainly do string concatenation, calculate a string and then bind a string to class or style... this method is error-prone and cumbersome at times to deal with. That's where Vue.js's clean suite of enhancements come into vue ( french for 'view' )
template
to the data available in your script
tag, which can be props, data or computed properties.v-bind
.<div
v-bind:class="dynamicClass"
>Hello World!
</div>
:
and then the attribute name, which I guess anyone would prefer using more.<div
:class="dynamicClass"
>Hello World!
</div>
computed
property or watch
to make changes to our dynamicClass
variable. So things will start to look like this.export default {
data( ) {
return {
changingBoolean: false
}
},
computed: {
dynamicClass: ( ) => changingBoolean : 'text-center text-lg' ? 'text-justify text-xl'
}
}
Looking at the code above we can see that for a simple switch in classes based on a variable we had to write so much code. So simply creating a dynamic class won't work.
<article
:class="[changingBoolean : ? 'text-center' : 'text-justify']"
>
Hello World!
</aside>
<article
:class="[changingBoolean : ? 'text-center' : 'text-justify', 'flex w-2']"
>
Hello World!
</aside>
true
and nothing when it's false
. Using ternary operator it will look as below:class = [changingBoolean : ? 'text-center' : ' ', 'flex w-2']
:class = [ { 'text-center' : changingBoolean }, 'flex w-2']
<article
class="absolute"
:class="{ active: isActive, 'text-xl': largeText }"
></article>
active
is a simple string variable for class whereas isActive
and largeText
are boolean variables. Also if you noticed class and :class
can simultaneously exist on a single element ツ
array/object
stored in our data
or computed
to classes. This can be a more powerful pattern at times when you have to do multiple checks and toggling which when accommodated into HTML won't look good and readable.<nav :class="classObject"></nav>
<my-icon
:class="text-blue-600"
/>
:class
will be appended at the end of the class inside of our component's parent. We can obviously also provide in a simple class
too.<nav
:style="{ marginTop: marginTop + 'px', backgroundColor: infoColor }"
>Doge Coin
</nav>
color
property a dynamic value and a similar operation for fontSize
.style
which is a more readable and cleaner method.<nav
:style="[marginObject, backgroundObject]"
>Doge Coin
</nav>
<ul :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></ul>