使用 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将博客内容html导出为Markdown格式

《Python将博客内容html导出为Markdown格式》Python将博客内容html导出为Markdown格式,通过博客url地址抓取文章,分析并提取出文章标题和内容,将内容构建成html,再转... 目录一、为什么要搞?二、准备如何搞?三、说搞咱就搞!抓取文章提取内容构建html转存markdown

在React中引入Tailwind CSS的完整指南

《在React中引入TailwindCSS的完整指南》在现代前端开发中,使用UI库可以显著提高开发效率,TailwindCSS是一个功能类优先的CSS框架,本文将详细介绍如何在Reac... 目录前言一、Tailwind css 简介二、创建 React 项目使用 Create React App 创建项目

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

Linux系统配置NAT网络模式的详细步骤(附图文)

《Linux系统配置NAT网络模式的详细步骤(附图文)》本文详细指导如何在VMware环境下配置NAT网络模式,包括设置主机和虚拟机的IP地址、网关,以及针对Linux和Windows系统的具体步骤,... 目录一、配置NAT网络模式二、设置虚拟机交换机网关2.1 打开虚拟机2.2 管理员授权2.3 设置子

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain