[英]Conditional style rendering with Vue.js
我有一个渲染元素的组件。 每个元素的宽度取决于minimized
值( true
或false
)。 我需要没有类的条件样式绑定。
我试过了:
{ conversation.minimized == false ? right: $index * 285 + 'px' : right: $index * 150 + 'px' }
但它没有用,我得到了错误。
我不确定你要做什么。 但你想让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>
标签进行操作有很多逻辑。
我真的没有你的代码,但如果你想要条件样式绑定,你可以这样做:
<template>
<div
:style="condition ? { 'color': 'red' } : { 'color': 'blue' }"
>
Some data
</div>
</template>
<script>
export default {
data() {
return {
condition: false
}
}
}
</script>
为了使事物更加模块化,我们可以创建一个组件来包装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'
}
}
}
} );
它接收index
和minified
值,然后使用计算函数来获取div样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.