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

相关文章

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.