使用 Vue.js 进行条件样式渲染

Conditional style rendering with Vue.js

本文关键字:样式 条件 Vue js 使用      更新时间:2023-09-26

我有一个渲染元素的组件。每个元素的宽度取决于minimized值(truefalse)。我在这里需要没有类的条件样式绑定。

我试过了:

{ conversation.minimized == false ? right: $index * 285 + 'px' : right: $index * 150 + 'px' }

但它没有用,我得到了错误。

我真的不明白你的代码,但如果你想要条件样式绑定,你可以这样做:

<template>
    <div
        :style="condition ? { 'color': 'red' } : { 'color': 'blue' }"
    >
        Some data
    </div>
</template>
<script>
export default {
    data() {
        return {
            condition: false
        }
    }
}
</script>

我不确定你想做什么。 但是你想让一个div变小还是变大?如果是这样,则可以使用计算的 var 来评估该值。因为它是反应性的,如果你改变这些值中的任何一个,它都会动态评估该值。

一个小例子:

<style>
  .classA {float:right,width:200px}
  .classB {float:right,width:400px}
</style>

在您的 HTML 上

<div id="#app">
<div class="{{ classChanger }}">your stuff</div>
</div>

和你的 Vue

computed:{
    classChanger: function(){
        var theClass = 'classB';
        if(this.conversation.minimized == false){
            theClass = 'classA';
        }
        return theClass:
    }
}

如果不确切了解您的代码,那就更难了。

currentItemPosition: function(index, conversation) {
            var indexOfCurrentElement = this.conversations.indexOf(conversation);  
            var right = 0;
            if (indexOfCurrentElement > 0) {
                for (var i=0; i<indexOfCurrentElement; i++) {
                    if (!this.conversations[i].minimized) {
                        right += 285;
                    } else {
                        right += 170;
                    }
                }
                return "right: " + right + "px";
            } else {
                return "right: 0px";
            } 
        }
    }

这就是我解决问题的方式。

<div class="card" v-bind:style="currentItemPosition($index, conversation)">

现在对我来说非常有效。无论如何,按照标签做<div>有很多逻辑。

为了使事情更加模块化,我们可以创建一个组件来包装div 和样式的逻辑。用法是:

<card :index="$index" :minimized="conversation.minimized"></card>

组件的定义是:

Vue.component( 'card', {
    props: ['index', 'minimized'],
    template: ''
        <div class="card" :style=[cardStyles]>'
    ',
    computed: function () {
        cardStyles: function () {
            var ratio = this.minimized ? 150 : 285;
            return {
                right: ( this.index * ratio ) + 'px'
            }
        }
    }
} );

它接收indexminified值,然后使用计算函数获取div 样式。