1.版本选择
vue2使用以下方式引入
import { loadModule } from 'vue3-sfc-loader/dist/vue2-sfc-loader.js';
vue3使用以下方式引入
import { loadModule } from 'vue3-sfc-loader/dist/vue3-sfc-loader.js';
注意,如果使用的vue3为3.4以前的版本,安装的vue3-sfc-loader版本要使用0.8.4或更早版本,3.4以后的版本需要安装0.9.0及以后版本的vue3-sfc-loader
2.载入模块
// 加载 async load (url) { const com = defineAsyncComponent(() => loadModule(url, { moduleCache: { vue: Vue }, async getFile(url) { const res = await fetch(url); if ( !res.ok ) throw Object.assign(new Error(res.statusText + ' ' + url), { res }); return Promise.resolve(res.text()); }, addStyle(textContent) { const style = Object.assign(document.createElement('style'), { textContent }); const ref = document.head.getElementsByTagName('style')[0] || null; document.head.insertBefore(style, ref); }, })); this.remote = markRaw(com); }
3.模块渲染
<component :is="remote" v-if="remote" style="height: 90%;width: 90%" />
上述代码亲测有效,并已应用在项目中