Home > Software design >  How to loop through component names?
How to loop through component names?

Time:12-01

I would like to display all the component names I imported to my XYZ View (and display it in cards). I need to somehow store component names in data property as to loop through it in template later. I tried to refer to components property from within data property using this.components but it doesn't work. I don't want to use names: ['A', 'B', 'C'] in data and loop through it, it's not a smart and efficient way even though this solution works. How can I get component names then?

<template>
  <v-container fluid>
    <v-row dense>
      <v-col
        v-for="(comp, n) in names"
        :key="n"
        :cols="n === 0 ? 2 : 10"
        >
        
          <v-card outlined tile>
            <component :is="comp"></component>
          </v-card>

      </v-col>

    </v-row>
  </v-container>
</template>

<script>
import A from '../views/A.vue';
import B from '../views/B.vue';
import C from '../views/C.vue';

export default {
  name: 'XYZ',
  data() {
    return {
      names: this.components,
      // names: ['A', 'B', 'C']   // I don't want to make it this way even though it works fine
    }
  },
  components: {
    A,
    B,
    C
  },
};
</script>

CodePudding user response:

Use this.$options.components - Docs

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Look here your code with a few modification

enter link description here

  • Related