运行中动态加载远程vue文件,解析template、script、style并注册全局组件:

(1).通过http请求获取组件数据,然后使用http-vue-loader插件解析script(解析为各生命周期钩子函数和methods对象),然后动态注册为vueComponent使用。 通过:is 来动态切换组件。

必须使用全量vue库,因为需要Vue来解析template模板为render函数。

vue-cli中默认使用的时运行时vue库,需要配置vue.config.js加入vue运行时编译模块:

module.exports = { runtimeCompiler: true, }

复制代码
import httpVueLoader from "http-vue-loader";
const mTpl = await DictionaryInfo(filter);//axios调用
 // 调用接口获取动态组件数据:{ template:  "<div class=\"main\"> xxx </div> ", script:  "module.exports = {data() {}, mounted() {}, methods: {} }", style: ".main { width: 100% }"
If(!mTpl?.script) return;
loadStyleString(mTpl.style);//读取配置中的css,加入到页面
const scriptStr= `<script>${mTpl.script}<\/script>`;
//解析script字符串
httpVueLoader("data:text/plain," + encodeURIComponent(scriptStr))().then(compiler => {
  Vue.component(mTpl.name, { mixins: [compBase], template: mTpl.template, ...compiler });
});
function loadStyleString(cssText) {//Chrome 112:CSS 支持嵌套语法,可以直接写嵌套css了
  var style = document.createElement("style");
  try {  style.appendChild(document.createTextNode(cssText));  } catch (ex) {
    // IE早期的浏览器 ,需要使用style元素的stylesheet属性的cssText属性
    style.styleSheet.cssText = cssText;
  }
  document.getElementsByTagName("head")[0].appendChild(style);
}

(2).也可以****使用vue2-sfc-loader来解析template script(template解析为render函数,script解析为各生命周期钩子函数和methods对象)****后再注册为VueComponent。

可以只使用运行时vue库,因为template已由vue2-sfc-loader解析了,可不用全量vue库。

复制代码
const tpl = await DictionaryInfo(filter);//axios调用
 // 调用接口获取动态组件数据:{ template:  "<div class=\"main\"> xxx </div> ", script:  "module.exports = {data() {}, mounted() {}, methods: {} }", style: ".main { width: 100% }"
const options = {
    moduleCache: {  vue: Vue },
    getFile(url) {
        return `${tpl.template}<script>${tpl.script}<\/script><style>${tpl.style}<\/style>`;
    },
    addStyle(textContent) {//Chrome 112:CSS 支持嵌套语法,可以直接写嵌套css了
        const style = document.createElement("style");
        try {   style.appendChild(document.createTextNode(textContent));  } catch (ex) {
        // IE早期的浏览器 ,需要使用style元素的stylesheet属性的cssText属性
            style.styleSheet.cssText = textContent;
        }
        document.getElementsByTagName("head")[0].appendChild(style);
    }
}
const pl = await loadModule('/xxx.vue', options);//解析后返回render函数、生后周期钩子函数、methods组成的对象
if (pl)  Vue.component(tpl.name, { mixins: [mixins], ...pl })
相关推荐
abigale031 小时前
webpack+vite前端构建工具 -11实战中的配置技巧
前端·webpack·node.js
专注API从业者1 小时前
构建淘宝评论监控系统:API 接口开发与实时数据采集教程
大数据·前端·数据库·oracle
Joker`s smile1 小时前
Chrome安装老版本、不同版本,自制便携版本用于前端调试
前端·chrome
weixin_416639972 小时前
爬虫工程师Chrome开发者工具简单介绍
前端·chrome·爬虫
我是如子啊2 小时前
【解决“此扩展可能损坏”】Edge浏览器(chrome系列通杀))扩展损坏?一招保留数据快速修复
前端·chrome·edge
灵性花火2 小时前
Qt的前端和后端过于耦合(0/7)
开发语言·前端·qt
孤水寒月6 小时前
基于HTML的悬窗可拖动记事本
前端·css·html
祝余呀6 小时前
html初学者第一天
前端·html
脑袋大大的7 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
速易达网络8 小时前
RuoYi、Vue CLI 和 uni-app 结合构建跨端全家桶方案
javascript·vue.js·低代码