0

I'm trying to generate an array of Vue Components based on a config file I have of the different UI sections to show;

const config = [
  'summarySection',
  'scoreSection',
  'educationSection'
]

So somehow I'm trying to map this into an array of vue components that I can use in my template. I was thinking about doing something like this;

const availableComponents = {
  'summarySection': <summary-section/ >,
  'scoreSection': <score-section/>,
  ...
}

const sections = config.map((section) => availableComponents[section])

<template v-for="section in sections">
  {{ section }}
</template>

But this clearly doesn't work :/. Any suggestions?

SOLUTION

Here's how I solved this;

// In my config file;
const sections = [
  'profile-summary-section',
  'matchbars-section',
  'job-experience-section',
  'education-section',
  'skills-section',
  'about-section',
  'availability-section',
  'recruiter-notes-section',
  'transport-section',
]

// In my template;
<template v-for="section in sections">
  <component :is="section" :key="section" v-bind="sectionProps[section]"></component>
</template>

// In my computed variables;
sectionProps() {
  return {
    'profile-summary-section': {
      vIf: this.showSummary,
      class: 'mb-2 has-light-border bg-white',
      profile: this.profile,
      number: 0,
      showMatchPercentage: false,
    },
    'matchbars-section': {
     ...
    },
  };
},
Simon Somlai
  • 856
  • 8
  • 16

2 Answers2

2

Use dynamic components.

const sections = ['summary-section', 'score-section'];

<template v-for="section in sections">
  <component :is="section"></component>
</template>

However, section should just hold the name of the registered component.

tony19
  • 125,647
  • 18
  • 229
  • 307
oshell
  • 8,923
  • 1
  • 29
  • 47
  • 2
    How would you add custom props for each component? Using the v-bind directive? https://stackoverflow.com/questions/43658481/passing-props-dynamically-to-dynamic-component-in-vuejs. – Simon Somlai Feb 24 '20 at 12:37
0

Array sections should be a part of Vue component data, so that you'd be ablate access it in v-for. Also note that manipulations on the array should also be done inside Vue instance's special methods.