【问题标题】:Loop Over Array Of Vue Components循环遍历 Vue 组件数组
【发布时间】:2020-06-08 02:03:03
【问题描述】:

我正在尝试根据我拥有的要显示的不同 UI 部分的配置文件生成 Vue 组件数组;

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

所以不知何故,我试图将它映射到我可以在我的模板中使用的一组 vue 组件中。我正在考虑做这样的事情;

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

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

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

但这显然行不通:/。有什么建议吗?

解决方案

我是这样解决这个问题的;

// 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': {
     ...
    },
  };
},

【问题讨论】:

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

使用dynamic components

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

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

但是,section 应该只包含注册组件的名称。

【讨论】:

【解决方案2】:

数组部分应该是 Vue 组件数据的一部分,这样你就可以在 v-for 中访问它。还要注意,数组的操作也应该在 Vue 实例的特殊方法中完成。

【讨论】:

    猜你喜欢
    • 2019-09-04
    • 2018-05-30
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2019-07-10
    • 2021-05-21
    相关资源
    最近更新 更多