一般问题:,我想知道是否可以根据条件连接类属性。请参阅v-for行中的伪代码。
我的用例:我想对齐所有在右边有一个偶数索引的图像。
如果我使用flex flex-row-reverse作为父部分,则图像在右边对齐。但是,我不知道如何构造类,这样我就不必为子元素重复代码。
<section
v-for="(quote, index) of $frontmatter.quotes :class="lg:flex my-4 mx-12 overflow-auto" + {even: index % 2, odd: !(index % 2)}"
>
<img
class="quote-image right rounded-full h-64 w-64 flex items-center justify-center shadow-md mx-auto lg:ml-16 lg:mr-10 mt-12"
:src="$withBase(quote.image)"
/>
<div class="px-8 pt-6">
<h3 class="text-primary font-bold mb-4">
{{ quote.title }}
</h3>
<p>
{{ quote.text }}
</p>
</div>
</section>并调用类扩展,类似于:
.even {
flex-row-reverse
}目前,我使用这个结构-但是,我对此不满意,因为我必须为子元素重复我的代码.
<section
v-for="(quote, index) of $frontmatter.quotes"
class= "my-16 mx-24 overflow-auto"
>
<div v-if="index % 2"
class="lg:flex flex-row-reverse">
<img
class="quote-image rounded-full h-64 w-64 flex items-center justify-center shadow-md mx-auto lg:ml-16 lg:mr-10 mt-12"
:src="$withBase(quote.image)"
/>
<div class="px-8 pt-6">
<blockquote>
<h2 class="text-primary font-bold mb-4">
{{ quote.title }}
</h2>
</blockquote>
<p class="quote-text">
{{ quote.text }}
</p>
</div>
</div>
<div v-else
class="lg:flex">
<img
class="quote-image rounded-full h-64 w-64 flex items-center justify-center shadow-md mx-auto lg:ml-16 lg:mr-10 mt-12"
:src="$withBase(quote.image)"
/>
<div class="px-8 pt-6">
<blockquote>
<h2 class="text-primary font-bold mb-4">
{{ quote.title }}
</h2>
</blockquote>
<p class="quote-text">
{{ quote.text }}
</p>
</div>
</div>
</section>它应该看起来像:

发布于 2019-12-08 23:09:09
首先,为了澄清我想要回答的问题。考虑到以下代码:
<div v-if="index % 2" class="lg:flex flex-row-reverse">
... children ...
</div>
<div v-else class="lg:flex">
... identical children ...
</div>是否有一种方法可以避免v-if并有条件地添加flex-row-reverse类?
你有很多选择。首先,属性class和style具有特殊的行为,允许您同时指定同一属性的绑定副本和静态副本。对于其他属性,您不能这样做。例如:
<div
class="lg:flex"
:class="{ 'flex-row-reverse': index % 2 }"
>因此,类lg:flex是作为静态类添加的,而flex-row-reverse是有条件地添加的。Vue将适当地将它们组合起来,以创建完成的DOM节点的class属性。
还有许多其他的方法可以写这个。下面是几个需要思考的问题:
<div :class="{ 'lg:flex': true, 'flex-row-reverse': index % 2 }"><div :class="['lg:flex', { 'flex-row-reverse': index % 2 }]">数组可以任意深度嵌套。普通字符串将被视为要添加的类。对象将被视为条件类的集合,类名为属性名,条件为属性值。
所有这些都是使用Vue对有条件添加类的支持。但是,绑定表达式只是任意的JavaScript,因此您可以使用普通的JavaScript语法来应用条件性,而不是让Vue为您执行它。
这通常比较笨重。这必须是一个表达式,所以不能使用if/else。但是,您可以使用?::
<div :class="'lg:flex' + (index % 2 ? ' flex-row-reverse' : '')">构建类的各种方法的正式文档如下:
https://v2.vuejs.org/v2/guide/class-and-style.html#Binding-HTML-Classes
发布于 2019-12-08 18:33:14
由于您使用的是类,而不是<b-img>道具,所以您需要的类可能是float-right而不是right。
<img v-if="index % 2"
class="quote-image float-right rounded-full h-64 w-64 shadow-md mx-auto lg:ml-16 lg:mr-10 mt-12"
:src="$withBase(quote.image)"
/>https://stackoverflow.com/questions/59238252
复制相似问题