使用 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

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删