使用vue3-sfc-loader实现远程组件预览

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%" />

上述代码亲测有效,并已应用在项目中

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值