v-bind 中的条件:样式

新手上路,请多包涵

我有一个简单的问题,希望你能帮忙:

 <div>
  <figure :style="{ 'background': 'url(' + item.main_featured + ') center no-repeat' }">
</div>

如果来自 API 的 URL 未定义,我希望样式属性“背景”返回颜色

例子:

如果 item.featured_photo 不为空:

 <figure style="background: url('localhost:6969/image.img') center no-repeat">

如果 item.featured_photo 为空:

 <figure style="background: #FFF">

原文由 KitKit 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 518
2 个回答

V-bind:style VueJS 中的使用条件:

 v-bind:style= "[condition ? {styleA} : {styleB}]"

这是最小的例子,

 <figure :style="[item.main_featured ? {'background': 'url(' + item.main_featured + ') center no-repeat'} : {'background': '#FFF'}]">

如果您需要 Parent-Child-Conditions ,那么这就是魔法:

 v-bind:style= "[condition_1 ? condition_2 ? {styleA} : {styleB} : {styleC}]"

简而言之:

 if (condition_1) {
   if (condition_2) {
      return styleA
   } else {
      return styleB
   }
} else {
  return styleC
}

希望能帮助到你!

原文由 KitKit 发布,翻译遵循 CC BY-SA 4.0 许可协议

以前的参考资料非常好,但对我来说真正有效的是:

 <input type="text"
v-bind:style=" boolVariable ? 'border: 1px solid orange;' : 'border: none;' ">

在文档中: https ://v2.vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions

问候!

原文由 Jhon Didier Sotto 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题