VueJS: v-bind:style only working conditionally in v-for
javascript, v-for, vue.js
Solution
Object keys must be properly quoted if you use key names that are not valid identifiers. So `v-bind:style="{ background-color: '#' + tradingCardOption.BorderColorHex}"`
must be
v-bind:style="{'background-color': '#' + tradingCardOption.BorderColorHex}"
because `background-color` can't be used as object property key unless surrounded with quotes. Same with `border-color` it should be:
{'border-top': '15px solid #' + tradingCardOption.CornerColorHex}
Basically, you need to make sure parser doesn't try to interpret `-` character as minus and then think that `border` is a variable.
Problem
Using `v-bind:style` works fine when binding `color`: ``` <p v-bind:style="{ color: '#' + tradingCardOption.BorderColorHex }"> {{ tradingCardOption.ColorSetName }} </p> ``` But, binding to the `background-color` does not work: ``` v-bind:style="{ background-color: '#' + tradingCardOption.BorderColorHex }" ``` And neither does binding to `border-top`: ``` v-bind:style="{ border-top: 15px solid + '#' + tradingCardOption.CornerColorHex }" ``` What could cause this to work so conditionally? ``` <div v-for="tradingCardOption in tradingCardOptions"> <div v-bind:style="{ background-color: '#' + tradingCardOption.BorderColorHex}" class="color-swatch " v-bind:class="{'selected' : $index == 0}" v-on:click="selectTradingCardOption(tradingCardOption, $event)"> <div v-bind:style="{ border-top: 15px solid + '#' + tradingCardOption.CornerColorHex}"></div> </div> {{ tradingCardOption.BorderColorHex}} <p v-bind:style="{ color: '#' + tradingCardOption.BorderColorHex}"> {{ tradingCardOption.ColorSetName }}</p> </div> ```