Vuejs 三元运算符/条件在 v-bind-style 中不起作用

Vuejs Ternary Operator / Conditional Not Working in v-bind-style

我在尝试为 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;
    },
  }

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

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

我错过了什么?

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

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

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

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

<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>

您的解决方案无效,因为您生成了双大括号

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

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

例如

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

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

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