Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.JS v-bind:style syntax not working?

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!

like image 359
Derek Avatar asked Dec 01 '16 18:12

Derek


People also ask

How do I add styles to Vuejs?

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.

What does V-bind do in Vue?

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.

What is the difference between V-model and V-bind?

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.

What is the shorthand for V-bind in Vue?

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.


1 Answers

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 }">
like image 117
asemahle Avatar answered Oct 20 '22 07:10

asemahle