运行中动态加载远程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 })
相关推荐
程序猿阿伟1 小时前
《首屏加载优化手册:Vue3+Element Plus项目提速的技术细节》
前端·javascript·vue.js
麦麦大数据1 小时前
D030知识图谱科研文献论文推荐系统vue+django+Neo4j的知识图谱|论文本文相似度推荐|协同过滤
vue.js·爬虫·django·知识图谱·科研·论文文献·相似度推荐
尘觉1 小时前
面试-浅复制和深复制?怎样实现深复制详细解答
javascript·面试·职场和发展
fruge2 小时前
Vue Pinia 状态管理实战指南
前端·vue.js·ubuntu
绝无仅有3 小时前
某教育大厂面试题解析:MySQL索引、Redis缓存、Dubbo负载均衡等
vue.js·后端·面试
sean3 小时前
开发一个自己的 claude code
前端·后端·ai编程
用户21411832636023 小时前
dify案例分享-用 Dify 一键生成教学动画 HTML!AI 助力,3 分钟搞定专业级课件
前端
chxii3 小时前
ISO 8601日期时间标准及其在JavaScript、SQLite与MySQL中的应用解析
开发语言·javascript·数据库
没逛够3 小时前
Vue 自适应高度表格
javascript·vue.js·elementui
太过平凡的小蚂蚁5 小时前
Kotlin 协程中常见的异步返回与控制方式(速览)
开发语言·前端·kotlin