Home > database >  creating a loop to loop over the componennt created
creating a loop to loop over the componennt created

Time:05-05

I have this data which is returning me the labels and every I need to create a component.

The component is already built when I pass the values. Now I want to create it as a for loop so that I can keep on adding entries, and it will create components as needed.

This is what I've tried:

data() {
  return {
    options: [{

        heading: 'Welcome to the Card',
        subheading: 'Manage your Profile here'
      },
      {

        heading: 'Pay your bills',
        subheading: 'Manage your bills and payments here'
      }
    ]
  }
}

I am trying to loop it over like this

<div v-for="(value, key) in options">
  <componentName {{key}} = {{value}}/>  
</div>

Previously, the above code was like this:

<componentName :heading='Welcome to the Card' :subheading='Manage your Profile here'/>

Which works well but to add more I have to recreate this <componentName which I want to avoid. I want to keep one entry and feed it with array of objects

I'm using Vue2. What am I doing wrong here?

CodePudding user response:

You're very close. Given your data, the template would need to look like:

<div v-for="(option, index) in options" :key="index">
  <h3>{{ option.heading }}</h3>
  <p>{{ option.subheading}}</p>
</div>

Or, if you've got a custom component, which takes heading and subheading as props:

<componentName
  v-for="(option, index) in options"
  :key="index"
  :heading="option.heading"
  :subheading="option.subheading"
/>

If you can share a bit more of your code, I can create a runnable snippet, if that would be helpful.

  • Related