Home > Software design >  How to dynamically add components to grid?
How to dynamically add components to grid?

Time:12-01

I created a grid using v-for. I need to add components to each column I created, each one in seperate column. I created view in script, where I store components but still I can't add them to each column separately:

<template>
  <v-container fluid>
    <v-row dense>
      <v-col
        v-for="n in 2"
        :key="n"
        :cols="n === 1 ? 2 : 10">

          <v-card outlined tile>
             <component :is="view"></component>
          </v-card>

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

<script>
import XYZ from '../views/XYZ.vue';
import AAA from '../views/AAA.vue';

export default {
  name: 'Project',
  data: {
      view: 'dynamic_views', 
  },
  components: {
    'dynamic_views': {
      XYZ,
      AAA
    }
  },
};
</script>

CodePudding user response:

Put the components directly inside the components option then create a data property called componentNames which you should loop through it :


import XYZ from '../views/XYZ.vue';
import AAA from '../views/AAA.vue';

export default {
  name: 'Project',
   data:{
      componentNames:['XYZ','AAA']
  },
  components: {
      XYZ,AAA
   
  },
};



in template :


<template>
  <v-container fluid>
    <v-row dense>
      <v-col
        v-for="(comp,n) in componentNames"
        :key="n"
        :cols="n === 1 ? 2 : 10">

          <v-card outlined tile>
             <component :is="comp"></component>
          </v-card>

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

  • Related