05. Class and Style Bindings Flashcards
Binding HTML Classes
“Object Syntax”
We can pass an object to v-bind:class to dynamically toggle classes.
You can have multiple classes toggled by having more fields in the object.
he v-bind:class directive can also co-exist with the plain class attribute.
Array Syntax
We can pass an array to v-bind:class to apply a list of classes:
<div></div> data: { activeClass: 'active', errorClass: 'text-danger' }
Condicionales en las clases
If you would like to also toggle a class in the list conditionally, you can do it with a ternary expression:
<div></div>
With Components
When you use the class attribute on a custom component, those classes will be added to the component’s root element. Existing classes on this element will not be overwritten.
Binding Inline Styles
Object Syntax
The object syntax for v-bind:style is pretty straightforward - it looks almost like CSS, except it’s a JavaScript object. You can use either camelCase or kebab-case (use quotes with kebab-case) for the CSS property names:
It is often a good idea to bind to a style object directly so that the template is cleaner:
<div></div>
data: { styleObject: { color: 'red', fontSize: '13px' } }
Again, the object syntax is often used in conjunction with computed properties that return objects.
Array Syntax
The array syntax for v-bind:style allows you to apply multiple style objects to the same element:
Auto-prefixing
When you use a CSS property that requires vendor prefixes in v-bind:style, for example transform, Vue will automatically detect and add appropriate prefixes to the applied styles.
Multiple Values
Starting in 2.3.0+ you can provide an array of multiple (prefixed) values to a style property, for example:
<div></div>
This will only render the last value in the array which the browser supports. In this example, it will render display: flex for browsers that support the unprefixed version of flexbox.