Home > Back-end >  Vue Vuetify Nuxt - Render a list of components in a v-for loop
Vue Vuetify Nuxt - Render a list of components in a v-for loop

Time:02-24

My situation

I've got a bunch of custom components that I want to put into tabs

import UserTable from '...'
import User from '...'
.
.
components: { 
  UserTable, 
  User 
}

data () { 
  return { 
    listComponents: [ UserTable, User] 
  }
}

What I'd like to do

Something like the following

<v-tab-item v-for="i in listComponents">
  <slots item:i> // or similar
</v-tab-item>

to iterate imported components in the html part

The purpose

To be able to skip copy pasting

<v-tab-item>
  <component_number_1>
</v-tab-item>

repeatedly

CodePudding user response:

I think what you are looking for is Dynamic Components - Docs Vue@2 Docs Vue@3

You list should contain the Names of the component in string format like so:

components: { 
  UserTable, 
  User 
},
data () { 
  return { 
    listComponents: ['UserTable', 'User']
  }
}
<v-tab-item v-for="component in listComponents">
  <component v-bind:is="component"></component>
</v-tab-item>

My personal opinion: this looks like overkill unless you have more than 5 components that need to be displayed like this, as you lose some visibility in the template of what is used.

  • Related