【问题标题】:Vuejs Ternary Operator / Conditional Not Working in v-bind-styleVuejs 三元运算符/条件不工作在 v-bind-style
【发布时间】:2019-12-31 23:23:00
【问题描述】:

我在尝试为 Vuejs 中的项目样式实现条件时遇到了一些奇怪的行为。

我见过 S.O.关于如何通过插值字符串或计算样式对象实现三元组的帖子。我都试过了,但都不能正常工作。

给定这个 div:

<div 
    :class="{'radar__container':true,'inactive':inactive}"
    :style= "[inactive ? {getStyleRadarContainerInactive} : {getStyleRadarContainer}]"
  >

我会实现这种风格:

computed: {
    getStyleRadarContainer: function(){

        let styleRadarContainer = {
            left: this.radarItem.posX*100 + '%', 
            top: this.radarItem.posY*100 + '%',
            transform: 'translate(-50%,-50%) scale(' + this.radarItem.scale + ')',
            opacity: this.radarItem.opacity,
        }

        return styleRadarContainer;
    },
    getStyleRadarContainerInactive: function(){

        let styleRadarContainerInactive= {
            left: this.radarItem.posX*100 + '%', 
            top: this.radarItem.posY*100 + '%',
            transform: 'translate(-50%,-50%) scale(0)',
            opacity: this.radarItem.opacity,
        }

        return styleRadarContainerInactive;
    },
  }

这应该使这些项目中的每一个都缩小(因为 opacity 属性中的 scale(0) ),但样式属性根本不呈现。我还在 style 属性上尝试了一个内联三元组(因为比例是两个属性之间唯一变化的东西:

transform: 'translate(-50%,-50%) ' + inactive ? 'scale(' + radarItem.scale + ')' : 'scale(0)',

我错过了什么?

【问题讨论】:

    标签: javascript css vue.js conditional-statements ternary-operator


    【解决方案1】:

    您的解决方案不起作用,因为您生成了双花括号

      :style="[{ obj: { styleObject }}]" // This won't work
    

    您可以有一个包含 styleObjects 的数组,也可以只有一个 styleObject。

    例如

      :style="[ { color: 'blue' } ]"
      :style="{ color: 'blue' }"
    

    【讨论】:

    • 有趣,我不知道如果你提供一个对象数组,它会合并它们......谢谢你。这在某些时候可能有用:) 我会更新我的答案。
    • 是的,它们与右侧的对象属性合并,覆盖左侧的对象
    【解决方案2】:

    样式绑定需要一个对象。通过将三元括在方括号中,您将传入一个包含对象的数组,这是不必要的。此外,您将返回的对象包裹在三元组两侧的括号中,从而进一步嵌套它们。删除这些括号将可以正确处理返回的对象:

    <div 
        :class="{'radar__container':true,'inactive':inactive}"
        :style= "inactive ? getStyleRadarContainerInactive : getStyleRadarContainer"
      >
    

    附带说明,如果您将包含对象的变量添加到另一个对象而不指定属性名称,则变量名称将用作属性名称。

    var myObject = {
      property: 'value'
    };
    
    $('#output').html(JSON.stringify({myObject}));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="output"></div>

    【讨论】:

      【解决方案3】:

      如果你像这样使用spread operator 应该可以工作:

      :style= "[inactive ? {...getStyleRadarContainerInactive} : {...getStyleRadarContainer}]"
      

      【讨论】:

        【解决方案4】:

        尝试在 V-bind:style 中使用条件

        v-bind:style= "[condition ? {style_A} : {style_B}]"
        

        https://vuejs.org/v2/guide/class-and-style.html

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-12
          • 2016-12-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多