How to Dynamically Load Vue 2 Components in a Vue 3 Project
This tutorial explains how to integrate a pre‑built Vue 2 component library into a Vue 3 application by dynamically loading the Vue 2 runtime, creating an isolated Vue 2 instance, mounting the component to a dedicated DOM node, and leveraging props for data exchange, while keeping bundle size small.
Environment Preparation: Install Vue 2 dependencies
Because the shared component library is built with Vue 2, you must first install the Vue 2 runtime and the library via npm, otherwise imports will fail.
Installation commands
# Install Vue 2 runtime
npm install vue@2
# Install Vue 2 company public component
npm install @xxx/dist/navigation-componentsSolution Overview
The approach is to dynamically load the Vue 2 runtime and component, create an isolated Vue 2 instance inside a Vue 3 component, mount the Vue 2 component to a dedicated DOM node, and pass data through props.
Dynamic loading of Vue 2 runtime and target component.
Create an independent Vue 2 instance within a Vue 3 component.
Mount the Vue 2 component to a specified DOM element.
Communicate via props and events.
Implementation Details
1. Dynamically import resources
Dynamic import enables code splitting, reducing the main bundle size and improving first‑screen performance.
import Vue2 from 'vue2/dist/vue.runtime.min.js' // Vue 2 runtime
import * as vue2Component from 'xxx/navigation-components' // Vue 2 public componentBuild output example:
dist/
├── index.html
├── main.js (500KB) ← main code
├── vue2.chunk.js (34KB) ← Vue 2 runtime
├── nav.chunk.js (15KB) ← navigation component
└── main.cssBy loading these chunks on demand, the main bundle stays small and the page loads faster.
2. Create Vue 2 instance in a Vue 3 file
<script setup>
import { onMounted } from 'vue';
import Vue2 from 'vue2/dist/vue.runtime.min.js';
import vue2Component from 'xxx/navigation-components';
onMounted(async () => {
new Vue2({
el: '#nav-footer',
render: h => h(vue2Component)
});
});
</script>3. Reserve mount point in template
<template>
<div>
<!-- other Vue 3 content -->
<main>...</main>
<!-- placeholder for Vue 2 component -->
<div id="nav-footer"></div>
</div>
</template>Advantages Summary
Excellent compatibility – no changes to existing Vue 3 architecture.
Strong isolation – Vue 2 and Vue 3 instances run independently.
Performance optimization – on‑demand loading and code splitting.
Low maintenance – you can reuse existing Vue 2 components directly.
Conclusion
This method lets a Vue 3 project use Vue 2 components without major refactoring, improving compatibility, performance, and maintainability, making it suitable for migration phases.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
