[Vuejs]-How to loop through component names?

3👍

Use this.$options.componentsDocs

const componentA = {
  name: 'compA',
  template: `<h3>Hi from compA</h3>`
}

const componentB = {
  name: 'compB',
  template: `<h3>Hi from compB</h3>`
}

new Vue({
  el: "#app",
  components: {
    componentA,
    componentB
  },
  data() {    
    return {
      // do this if you want names by which the components are (locally) registered
      // this is much more usefull as you can use these names with <component :is="name">
      componentNames1: Object.keys(this.$options.components),
      
      // do this if you want names defined in components definition
      componentNames2: Object.entries(this.$options.components).map(entry => entry[1].name)      
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.js"></script>
<div id="app">
<div>1: {{ componentNames1 }}</div>
<div>2: {{ componentNames2 }}</div>
<hr>
<div v-for="name in componentNames1">
  <component :is="name" :key="name"></component>
</div>
</div>

Leave a comment