如何使用Webpack动态导入子模块?Vue嵌套组件场景技术问询
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 importedMarker.vueandWidget.vuefiles 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

