Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add conditions to a v-for in Vue

Is there possible to add conditions on looping out arrays in Vue? Like with the example down below, I loop an array of persons into a table:

    <CTableRow v-for="person in persons" :key="person.status">
      <CTableDataCell>{{ person.id }}</CTableDataCell>
      <CTableDataCell>{{ person.name }}</CTableDataCell>
      <CTableDataCell>{{ person.age }}</CTableDataCell>
    </CTableRow>

If I have an element in persons named "active" (i.e person.active) can I somehow only loop through persons who are active and further down the Vue file loop through the persons who are not active, using the same data source?

If I can use some pseudocode, I want to achieve something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    <CTableRow v-for="person in persons" :key="person.status">
      if( person.active === true) {
        <CTableDataCell>{{ person.id }}</CTableDataCell>
        <CTableDataCell>{{ person.name }}</CTableDataCell>
        <CTableDataCell>{{ person.age }}</CTableDataCell>
      }
    </CTableRow>
    
    <CTableRow v-for="person in persons" :key="person.status">
      if( person.active === false) {
        <CTableDataCell>{{ person.id }}</CTableDataCell>
        <CTableDataCell>{{ person.name }}</CTableDataCell>
        <CTableDataCell>{{ person.age }}</CTableDataCell>
      }
    </CTableRow>

Is this possible in Vue, and what would be the best practice?

Update:
I realized I could add a v-if on all the TableDataCells as a solution to my problem. Or is it better to create two arrays in the composition api?

>Solution :

You should be able to do this:

<CTableRow v-for="person in persons" :key="person.status">
    <template v-if="person.active">
        <CTableDataCell>{{ person.id }}</CTableDataCell>
        <CTableDataCell>{{ person.name }}</CTableDataCell>
        <CTableDataCell>{{ person.age }}</CTableDataCell>
    </template>
    <template v-else>
        <CTableDataCell>Something Else</CTableDataCell>
    </template>
</CTableRow>

The <template> is just a container which won’t get rendered.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading