Skip to content

v-for loop in vue.js

I am trying to iterate the object using v-for.

exampleObject =[a,b,c,d]
Requirement = if a exist in exampleObject, show only a, else show b, c, d.
 <div v-if="checklist.types">
      <div v-for="type in checklist.types">
         <div v-if="type.Name == 'Module1'">
              show module 1
         </div>
         <div v-else>
             <span>{{type.Name }}</span>
         </div>
     </div>
</div>

The above shows all values as the condition is checked within For Loop. Is there a way to iterate and check the object at the beginning.

Answer

I’d use a computed property that returns an array containing…

  1. Only a / Module1 if it exists
  2. The entire exampleObject / checklist.types otherwise

Then you can just iterate that computed property

export default {
  data: () => ({
    checklist: {
      types: [/* whatever */]
    }
  }),
  computed: {
    modules: ({ checklist: { types } }) => {
      const module1 = types.find(({ Name }) => Name === "Module1")
      return module1 ? [ module1 ] : types
    }
  }
}
<div v-for="module in modules" :key="module.Name">
  <span>{{ module.Name }}</span>
</div>