加载远程.vue文件并使用(Vue3版)

之前写了基于Vue2版的加载远程.vue组件,后面有友友问关于 Vue3 的版本,经过踩坑实践后写出来了记录一下。

vue3-sfc-loader 插件

Vue3/Vue2单文件组件加载器 在运行时从html/js/string动态加载.vue文件并转成响应式组件

loadModule 导入

Vue3 的导入路径和Vue2有点不一样,我这里使用esm版本

js 复制代码
// Vue3 esm 版
import { loadModule } from 'vue3-sfc-loader/dist/vue3-sfc-loader.esm.js'

获取Vue

因为Vue3 不默认导出Vue了,所以这里直接导入所有

js 复制代码
import * as Vue from 'vue'

远程加载

loadModule 第一个参数是组件路径字符串,会传入getFile方法中

getFilehttp 获取远程组件文件,此处我使用fetch API ,请求成功后调text() 返回 最终就是返回的一个字符串文本

这里使用Vue3 defineAsyncComponent 加载组件

js 复制代码
const options = {
  moduleCache: {
    vue: Vue,
  },
  async getFile (url: string) {
    return await fetch(url).then(res => res.text())
  },
  addStyle () {
    /* unused here */
  },
}
const asyncComponent = defineAsyncComponent(() => loadModule('/vue/v3test.vue', options))

渲染组件

渲染就使用 :is 动态渲染

同时传递属性和绑定事件

js 复制代码
<component :is="asyncComponent" v-bind="$attrs"/>

完整代码

js 复制代码
<template>
  <div>
    <component :is="asyncComponent" v-bind="$attrs"/>
  </div>
</template>

<script setup lang="ts">
import * as Vue from 'vue'
import { loadModule } from 'vue3-sfc-loader/dist/vue3-sfc-loader.esm.js'
import { defineAsyncComponent } from 'vue'
const options = {
  moduleCache: {
    vue: Vue,
  },
  async getFile (url: string) {
    return await fetch(url).then(res => res.text())
  },
  addStyle () {
    /* unused here */
  },
}
const asyncComponent = defineAsyncComponent(() => loadModule('/vue/v3test.vue', options))
</script>
相关推荐
哆啦A梦15881 天前
20, Springboot3+vue3实现前台轮播图和详情页的设计
javascript·数据库·spring boot·mybatis·vue3
Moment1 天前
面试官:如果产品经理给你多个需求,怎么让AI去完成❓❓❓
前端·后端·面试
每天吃饭的羊1 天前
JSONP
前端
gogoing1 天前
ESLint 配置字段说明
前端·javascript
Lkstar1 天前
面试官让我手写 Promise.all / Promise.race / Promise.allSettled,我直接水灵灵地写出来了
javascript·面试
gogoing1 天前
CSS 属性值计算过程(Computed Value)
前端·css
gogoing1 天前
webpack 的性能优化
前端·javascript
gogoing1 天前
Node.js 模块查找策略(require 完整流程)
javascript·node.js
桃花键神1 天前
Bright Data Web Scraping指南 2026: 使用 MCP + Dify 自动采集海外社交媒体数据
大数据·前端·人工智能
gogoing1 天前
await fetch() 的两阶段设计
前端·javascript