当前位置:   article > 正文

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

运行中动态加载远程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, }

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

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

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

  1. const tpl = await DictionaryInfo(filter);//axios调用
  2. // 调用接口获取动态组件数据:{ template: "<div class=\"main\"> xxx </div> ", script: "module.exports = {data() {}, mounted() {}, methods: {} }", style: ".main { width: 100% }"
  3. const options = {
  4.     moduleCache: {  vue: Vue },
  5.     getFile(url) {
  6.         return `${tpl.template}<script>${tpl.script}<\/script><style>${tpl.style}<\/style>`;
  7.     },
  8.     addStyle(textContent) {//Chrome 112:CSS 支持嵌套语法,可以直接写嵌套css了
  9.         const style = document.createElement("style");
  10.         try {   style.appendChild(document.createTextNode(textContent)); } catch (ex) {
  11.         // IE早期的浏览器 ,需要使用style元素的stylesheet属性的cssText属性
  12.             style.styleSheet.cssText = textContent;
  13.         }
  14.         document.getElementsByTagName("head")[0].appendChild(style);
  15.     }
  16. }
  17. const pl = await loadModule('/xxx.vue', options);//解析后返回render函数、生后周期钩子函数、methods组成的对象
  18. if (pl)  Vue.component(tpl.name, { mixins: [mixins], ...pl })

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/934858
推荐阅读
相关标签
  

闽ICP备14008679号