You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Webpack动态导入子模块?Vue嵌套组件场景技术问询

Solution: Register Child Components Locally in GoogleMapAsync.vue

Since you know <marker> and <widget> will only ever be used inside <google-map>, the cleanest approach is to locally register them directly within the GoogleMapAsync.vue component. This way, when you dynamically import the parent google-map component, its dependent child components will be loaded alongside it automatically—no need for separate global registrations.

Here's how to implement it step-by-step:

1. Import & Register Child Components in GoogleMapAsync.vue

At the top of your GoogleMapAsync.vue file, import the child components and register them locally (adjust file paths to match your project structure):

<template>
  <div class="google-map-container">
    <!-- Your existing template using <widget> and <marker> -->
    <widget />
    <marker />
  </div>
</template>

<script>
// Import the child components directly
import Marker from './Marker.vue'; // Adjust path if your Marker is in a subfolder
import Widget from './Widget.vue';

export default {
  // Locally register the components so they're available in the template
  components: {
    Marker, // Vue automatically converts this camelCase name to kebab-case (<marker>)
    Widget  // Converts to <widget> for the template
  },
  // Rest of your component logic (data, methods, lifecycle hooks, etc.)
}
</script>

2. Keep Your Existing Dynamic Parent Component Registration

Your original code for dynamically registering <google-map> stays exactly the same—no changes needed here:

Vue.component('google-map', () => import('@/components/maps/GoogleMapAsync.vue'));

Why This Works

  • No Global Pollution: The child components are only accessible to <google-map>, which aligns perfectly with your requirement that they won't be used elsewhere.
  • Coordinated Loading: When the browser fetches GoogleMapAsync.vue, your bundler (Webpack/Vite) will automatically fetch the imported Marker.vue and Widget.vue files as part of the same load process, ensuring all related components are ready at the same time.

If you're using Vue 3, the process is even cleaner with <script setup>—imported components are automatically registered locally:

<script setup>
import Marker from './Marker.vue';
import Widget from './Widget.vue';
</script>

<template>
  <div class="google-map-container">
    <widget />
    <marker />
  </div>
</template>

内容的提问来源于stack exchange,提问作者Stephan-v

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:09:04