[Vuejs]-Adding a class to top object int the list of dynamically changing objects

1👍

Dynamic Class

I’ll assume you really do need a computed, and that it will return various class names. (It’s quite possible you don’t.)

  • Let’s call it topClass, without the dash, it’s easier.

  • It’s unclear whether objects is an array of objects or an object hash of objects, so I’ll give both answers. If objects is:

Array

<article v-for="(item, index) in objects" :class="{ [topClass]: index === 0 }">

Object (using 3rd v-for argument index)

<article v-for="(item, key, index) in objects" :class="{ [topClass]: index === 0 }">

The [ ] brackets in the class binding are es2015 computed properties which allow dynamically referencing a key.

Here is a demo.


Static Class

On the other hand, if the class name won’t be dynamic, you don’t need a computed at all. You can just do:

Array

<article v-for="(item, index) in objects" :class="{ 'top-class': index === 0 }">

Object (using 3rd v-for argument index)

<article v-for="(item, key, index) in objects" :class="{ 'top-class': index === 0 }">
👤Dan

Leave a comment