在 Vue 3 中,要遍历 funConfig 并动态生成组件,可以使用 Vue 的 defineAsyncComponent 来加载异步组件,并结合 v-for 指令在模板中进行渲染。

以下是一个示例代码来实现这个需求:

1. 配置文件

确保配置文件导出的是一个 reactive 对象:

import { reactive, markRaw, defineAsyncComponent } from 'vue';

export const funConfig = reactive([
  {
    name: '航线规划',
    icon: 'fun-route',
    show: false,
    component: markRaw(
      defineAsyncComponent(() => import('@/views/Map/components/RouteBox/index.vue')),
    ),
  },
  {
    name: '海洋气象',
    icon: 'fun-weather',
    show: false,
    component: markRaw(
      defineAsyncComponent(() => import('@/views/Map/components/SeaCurrent/index.vue')),
    ),
  },
  {
    name: '船舶过滤',
    icon: 'fun-ship',
    show: false,
    component: markRaw(
      defineAsyncComponent(() => import('@/views/Map/components/ShipBox/index.vue')),
    ),
  },
  {
    name: '港口过滤',
    icon: 'fun-port',
    show: false,
    component: markRaw(
      defineAsyncComponent(() => import('@/views/Map/components/PortBox/index.vue')),
    ),
  },
]);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.

2. Vue 组件

在 Vue 组件中,使用 defineAsyncComponent 来动态加载组件,并使用 v-for 指令来遍历 funConfig

<template>
  <div>
  <component
    v-for="item in funConfig"
    v-model="item.show"
    :is="item.show ? item.component : null"
  ></component>
  </div>
</template>

<script setup>
import { funConfig } from './path/to/your/config/file';
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

直接在component循环,可能会存在错误,使用以下方式应该可以避免

<template v-for="item in funConfig">
    <component v-model="item.show" v-if="item.show" :is="item.component"></component>
  </template>
  • 1.
  • 2.
  • 3.