Reputation: 3738
how should I go about applying an attribute to a class for styling only for certain elements in a list? It will be clearer in the example below:
<u-col
v-for="(item, i) in items"
:key="i"
:class="classNames.viewport"
>
data () {
return {
classNames: {
viewport: "col-lg-3 col-md-3 col-sm-3 col-6 d-flex justify-content-center"
}
}
}
Assuming i
only goes from 0-3. Currently every item
in v-for
has the class viewport
for styling. What I am hoping to achieve is to only apply an additional margin style mb-3
if i
is greater than 1.
ie, the viewport
becomes "col-lg-3 col-md-3 col-sm-3 col-6 d-flex justify-content-center mb-3"
for items with i > 1, while viewport
does not contain mb-3
for items with i < 1.
I thought about using a v-for
and v-if
together but I believe it is not a good practice to do so, https://www.codecheef.org/article/dont-use-v-if-with-v-for-elements.
Upvotes: 0
Views: 199
Reputation: 377
You can use Vue's Class and Style bindings and pass it an object.
<u-col
v-for="(item, i) in items"
:key="i"
:class="{
'col-lg-3 col-md-3 col-sm-3 col-6 d-flex justify-content-center': true,
'mb-3': i > 1,
}"
/>
Upvotes: 1
Reputation: 4480
Try like this
:class="`${classNames.viewport} ${i > 1 ? 'mb-3' : ''}`"
Upvotes: 1
Reputation: 214987
In :class
bind, you can check i
and add mb-3
to class when i > 1
:
<u-col
v-for="(item, i) in items"
:key="i"
:class="classNames.viewport + (i > 1 ? ' mb-3' : '')"
>
Upvotes: 1