I'm fairly knew to Vue and the whole v-bind
thing is throwing me for a loop...
Basically, I'm trying to achieve this syntax, but with Vue's v-bind
, since I can't use a variable in an inline CSS style:
<div class="card" style="background-color: {{school.color}}">
Here's my Vue syntax, which I've followed from their documentation, but it's still throwing an error and I can't figure out why? Obviously, it has to be something simple, I just don't fully understand the intricacies of Vue yet!
<div class="card" :style="{ background-color: school.color }">
Any help would be much appreciated!
In Vue. js, we can add an inline style to our element by binding the style attribute in the HTML tag. For reference, :style is shorthand for v-bind:style . Inline styling can be done in two ways: using object syntax or array syntax.
The v-bind directive is a Vuejs directive used to bind one or more attributes, or a component prop to an element. If that attribute is binded to our data defined in Vuejs instance then dynamically changes can be observed as data changes.
v-bind is a one-way binding. v-model is used for binding form elements like inputs, radio buttons, textarea, checkboxes. It is used for binding data, attributes, expressions, class, styles. V-model is input value sensitive.
In the shorthand, everything before the argument (i.e. v-bind: ) is condensed into a single character, : . Here the argument is the event name to listen to: click . v-on has a corresponding shorthand, namely the @ character.
For object syntax bindings you are binding an object. Thus, the keys must be valid, and need to be quoted unless they are valid unquoted keys. Dashes -
are not allowed in unquoted keys, so it fails to compile.
Either of these options will work:
<div class="card" :style="{ 'background-color': school.color }">
or
<div class="card" :style="{ backgroundColor: school.color }">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With