FranckFreiburger / vue3-sfc-loader

Single File Component loader for Vue2 and Vue3. Load .vue files directly from your HTML. No node.js environment, no build step.
MIT License
1.03k stars 116 forks source link

Q: how to import component dynamicly #108

Closed mech01nc01 closed 2 years ago

mech01nc01 commented 2 years ago

Hello,

frist thanks foryour great work!!

i'm currently rewriting some code and i have a popup-component that will get a component-name and props but mostly the components are not loaded, so i thought i could just load them if missing

i can check if the component is aviable, i can fetch the component, but how can i "add" the loaded component to the current instance? (i know that this may be behind he scope of your project, but maybe you know?)

mech01nc01 commented 2 years ago

solved by:

getFile: async function(url)
            {
                const res = await fetch(url);

                if (!res.ok)
                {
                    throw Object.assign(new Error(res.statusText + ' ' + url), { res });
                }
                return {
                    getContentData: (asBinary) => asBinary ? res.arrayBuffer() : res.text(),
                }
            },
            async loadComponent()
            {
                let c=this.component;
                if(c===null) return;
                if(this.componentsLoaded[c]) return;
                const { loadModule, vueVersion } = window['vue2-sfc-loader'];
                const options = {
                    moduleCache:
                    {
                        vue: Vue,
                    },
                    getFile: this.getFile,
                    addStyle() { /* unused here */ },
                };
                let component = await loadModule('/js_include/vue/' + c + '.vue', options);
                this.$set(this.componentsLoaded,c,component);
            }