使用 vue3-sfc-loader 加载远程Vue文件, 在运行时动态加载 .vue 文件。无需 Node.js 环境,无需 (webpack) 构建步骤

本文主要是介绍使用 vue3-sfc-loader 加载远程Vue文件, 在运行时动态加载 .vue 文件。无需 Node.js 环境,无需 (webpack) 构建步骤,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

加载远程Vue文件

vue3-sfc-loader

vue3-sfc-loader ,它是Vue3/Vue2 单文件组件加载器。

在运行时从 html/js 动态加载 .vue 文件。无需 Node.js 环境,无需 (webpack) 构建步骤。

主要特征

  • 支持 Vue 3 和 Vue 2(参见dist/)
  • 仅需要 Vue 仅运行时构建
  • 提供esmumd捆绑包(示例)
  • 嵌入式ES6模块支持(含import()
  • TypeScript 支持、JSX 支持
  • 自定义 CSS、HTML 和脚本语言支持,请参阅pug和stylus示例
  • SFC 自定义块支持
  • 通过日志回调正确报告模板、样式或脚本错误
  • 专注于组件编译。网络、样式注入和缓存由您决定(参见下面的示例)
  • 轻松构建您自己的版本并自定义您需要支持的浏览器

编写Node接口

编写Node接口提供服务,用于返回vue文件

项目初始化和安装

mkdir nodeServe
cd nodeServe
npm iniy -y
npm install express cors

项目完整结构

nodeServer
├── index.js
├── loaderVue2.vue
├── loaderVue3.vue
├── package-lock.json
└── package.json

添加 index.js

// express 基于Node.js平台,快速、开放、极简的 Web 开发框架 https://www.expressjs.com.cn/
const express = require("express")
const app = express()
const cors = require("cors")
const fs = require('fs');// 配置cors中间件,允许跨域
app.use(cors())app.get("/getVue2Str", (req, res) => {// 服务端读取文件,并变成字符串。传递给前端const data = fs.readFileSync('./loaderVue2.vue', 'utf8');res.send({code:200,fileStr:data,fileName:"loaderVue2.vue"});
})app.get("/getVue3Str", (req, res) => {// 服务端读取文件,并变成字符串。传递给前端const data = fs.readFileSync('./loaderVue3.vue', 'utf8');res.send({code:200,fileStr:data,fileName:"loaderVue2.vue"});
})app.listen(3000, () => {console.log("服务启动成功:http://localhost:3000")
})

这里用到的两个vue文件代码如下

loaderVue2.vue

<template><div><h1>我是远程加载的组件</h1><input :value="value" @input="changeName" /><button @click="patchParentEvent">触发父组件方法</button></div>
</template>
<script>
export default {props: ["value"],methods: {changeName(e) {this.$emit("input", e.target.value);},patchParentEvent() {this.$emit("parentEvent");},},
};
</script><style scoped>
h1 {color: red;
}
</style>

loaderVue3.vue

<template><div><h1 class="text-red">我是远程加载的页面</h1><input v-model="input" placeholder="placeholder" @input="changeValue"/><button @click="emitParentFun">调用父组件的方法</button></div>
</template><script setup>
import {defineProps,defineEmits,ref,onMounted} from "vue"const props = defineProps(['modelValue'])
// 更新model绑定的值固定写法: update:modelValue
const emit = defineEmits(['update:modelValue',"childClick"])let input = ref("")onMounted(()=>{input.value = props.modelValue// window环境指向的是接收方的window环境console.log(window.testName);
})const changeValue = (e) => {// 修改父组件的值emit('update:modelValue',e.target.value)
}const emitParentFun = ()=>{emit('childClick',input.value)
}
</script><style scope>
.text-red{color: red;
}
</style>

运行

node index.js

image-20240411094407264

接口返回的格式如下

http://localhost:3000/getVue2Str

{"code": 200,"fileStr": "<template>\r\n  <div>\r\n    <h1>我是远程加载的组件</h1>\r\n    <input :value=\"value\" @input=\"changeName\" />\r\n    <button @click=\"patchParentEvent\">触发父组件方法</button>\r\n  </div>\r\n</template>\r\n<script>\r\nexport default {\r\n  props: [\"value\"],\r\n  methods: {\r\n    changeName(e) {\r\n      this.$emit(\"input\", e.target.value);\r\n    },\r\n    patchParentEvent() {\r\n      this.$emit(\"parentEvent\");\r\n    },\r\n  },\r\n};\r\n</script>\r\n\r\n<style scoped>\r\nh1 {\r\n  color: red;\r\n}\r\n</style>\r\n","fileName": "loaderVue2.vue"
}

Vue2项目使用

安装 vue3-sfc-loader

npm install vue3-sfc-loader

使用

注意:

vue2要从dist/vue2-sfc-loader这个目录下引入loadModule使用

vue2要从dist/vue3-sfc-loader这个目录下引入loadModule使用

<template><div><component :is="remote" v-bind="$attrs" v-if="remote" v-model="name" @parentEvent="parentEvent"></component></div>
</template><script>
import * as Vue from "vue"
import {loadModule} from "vue3-sfc-loader/dist/vue2-sfc-loader"export default {name: 'App',data() {return {name: "李四",remote: null,url: "http://localhost:3000/getVue2Str",}},mounted() {this.load(this.url)},watch: {name(newName) {console.log(newName, "监听到变化")}},methods: {// 加载async load(url) {let res = await fetch(url).then(res => res.json());const options = {moduleCache: {vue: Vue},async getFile() {return res.fileStr},addStyle(textContent) {const style = Object.assign(document.createElement('style'), {textContent})const ref = document.head.getElementsByTagName('style')[0] || nulldocument.head.insertBefore(style, ref)},};// 加载远程组件this.remote = await loadModule(res.fileName || "loader.vue", options)},// 子组件调用parentEvent() {console.log("父组件事件触发")}}
}
</script>

效果显示

image-20240411094551171

Vue3项目使用

安装

npm install vue3-sfc-loader

使用

注意:

vue2要从dist/vue2-sfc-loader这个目录下引入loadModule使用

vue2要从dist/vue3-sfc-loader这个目录下引入loadModule使用

<template><div><component :is="remote" v-if="remote" v-model="name" @childClick="childClick"/></div>
</template><script setup>
import {loadModule} from "vue3-sfc-loader/dist/vue3-sfc-loader"
import * as Vue from 'vue'
import {onMounted, defineAsyncComponent, ref, watchEffect} from "vue"let remote = ref()
let name = ref("李四")
let url = "http://localhost:3000/getVue3Str"onMounted(() => {load(url)
})watchEffect(() => {console.log(name.value)
})const childClick = (newVal) => {console.log("子组件点击事件", newVal)
}// 加载远程文件
const load = async (url) => {let res = await fetch(url).then(res => res.json());const options = {moduleCache: {vue: Vue},async getFile() {return res.fileStr},addStyle(textContent) {const style = Object.assign(document.createElement('style'), {textContent})const ref = document.head.getElementsByTagName('style')[0] || nulldocument.head.insertBefore(style, ref)},};// 加载远程组件remote.value = defineAsyncComponent(() => loadModule(res.fileName || "loader.vue", options))
}
</script>

image-20240411094814070

完整源码

https://gitee.com/szxio/load-remote-vue-components

😆 求Start

这篇关于使用 vue3-sfc-loader 加载远程Vue文件, 在运行时动态加载 .vue 文件。无需 Node.js 环境,无需 (webpack) 构建步骤的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/896565

相关文章

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

一文详解Git中分支本地和远程删除的方法

《一文详解Git中分支本地和远程删除的方法》在使用Git进行版本控制的过程中,我们会创建多个分支来进行不同功能的开发,这就容易涉及到如何正确地删除本地分支和远程分支,下面我们就来看看相关的实现方法吧... 目录技术背景实现步骤删除本地分支删除远程www.chinasem.cn分支同步删除信息到其他机器示例步骤

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

python删除xml中的w:ascii属性的步骤

《python删除xml中的w:ascii属性的步骤》使用xml.etree.ElementTree删除WordXML中w:ascii属性,需注册命名空间并定位rFonts元素,通过del操作删除属... 可以使用python的XML.etree.ElementTree模块通过以下步骤删除XML中的w:as