使用 Vue.js 进行条件样式渲染
Conditional style rendering with Vue.js
我有一个渲染元素的组件。每个元素的宽度取决于minimized
值(true
或false
)。我在这里需要没有类的条件样式绑定。
我试过了:
{ 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'
}
}
}
} );
它接收index
和minified
值,然后使用计算函数获取div 样式。
相关文章:
- Ionic V1.3-标签-带条件的徽章样式<离子选项卡>
- 使用jQuery按条件将样式设置为html标记
- CSS根据属性的可用性有条件地应用样式
- 条件滚动条样式
- 如何在 angularjs 中设置多个条件来设置样式
- 如何使用js有条件地更改css样式
- 如何使用JavaScript/jQuery有条件地添加样式表
- 在ng repeat中按条件设置格式/样式
- Angular JS - 具有动态数据的条件内联样式
- 有条件的取决于样式
- JavaScript 条件样式 “A && B ||C“与”A ?乙:丙”
- 如何将基于条件的样式应用于剑道 UI 网格
- 使用 Vue.js 进行条件样式渲染
- angular ng在条件下重复添加样式
- 基于javascript条件应用样式
- 在 EJS 中给出遵循 If 条件的样式
- 条件函数的无点样式
- xhtml文档没有读取条件样式表
- 如何基于边距样式创建If Else条件
- 根据条件更改按钮的样式(使用KnockoutJS)