Vue内联条件if?

Tho*_*rge 5 vue.js

我有以下一段代码:

    <div
        :id="'object' + object.id""
        :style="'position:absolute !important; width:' + object.width + '% !important; height:' + object.height + '% !important;'">
    <div
Run Code Online (Sandbox Code Playgroud)

这很好用,并且渲染得很好。

我现在想在那里添加有条件的东西。就像是

if object.background == 'solid'
 background-color: #ffffff;
endif
Run Code Online (Sandbox Code Playgroud)

我尝试通过 Vue 内联 if 来实现这一点,它给了我这个:

[object.background == 'solid' ?背景颜色:#ffffff 重要;:'']

但这只是带来了很多错误,这让我觉得我在处理这一切都是错误的。

对我来说,在我的风格中实现简短的条件语句的正确方法是什么?

Ste*_* B. 6

我将使用返回样式对象的计算属性。

new Vue({
  el: "#app",
  data: {
    width: '200px',
    height: '200px',
    background: 'solid',
  },
  computed: {
    styleObj() {
      return {
        position: 'absolute !important',
        width: `${this.width} !important`,
        height: `${this.height} !important`,
        background: this.background === 'solid' ? 'green' : 'yellow',
      };
    },
  },
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
<div id="app">
    <div :style="styleObj">    
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 计算属性具有缓存等优点。它也比在模板中更容易阅读。 (2认同)