VueJS:v-bind:样式仅在v-for中有条件地工作

J W*_*J W 4 javascript vue.js v-for

v-bind:style绑定时使用正常工作color:

<p v-bind:style="{ color: '#' + tradingCardOption.BorderColorHex }">
  {{ tradingCardOption.ColorSetName }}
</p>
Run Code Online (Sandbox Code Playgroud)

但是,绑定到background-color不起作用:

v-bind:style="{ background-color: '#' + tradingCardOption.BorderColorHex }" 
Run Code Online (Sandbox Code Playgroud)

也没有绑定到border-top:

v-bind:style="{ border-top: 15px solid + '#' + tradingCardOption.CornerColorHex }"
Run Code Online (Sandbox Code Playgroud)

是什么导致这种条件有条不紊地工作?

<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>
Run Code Online (Sandbox Code Playgroud)

dfs*_*fsq 6

如果使用非有效标识符的键名,则必须正确引用对象键.所以v-bind:style="{ background-color: '#' + tradingCardOption.BorderColorHex}"

一定是

v-bind:style="{'background-color': '#' + tradingCardOption.BorderColorHex}"
Run Code Online (Sandbox Code Playgroud)

因为background-color除非用引号括起,否则不能用作对象属性键.与border-color它相同应该是:

{'border-top': '15px solid #' + tradingCardOption.CornerColorHex}
Run Code Online (Sandbox Code Playgroud)

基本上,您需要确保解析器不会尝试将-字符解释为减号,然后认为这border是一个变量.

  • 现在这看起来很明显了,谢谢! (2认同)