VUE 3动态导入文件

发布于 2025-01-31 06:12:43 字数 2789 浏览 0 评论 0原文

我正在尝试构建VUE 3动态加载JSON文件,以创建网站构建器。因此每个页面都定义为JSON文件,以允许用户从后端更改JSON文件(所有组件都在该文件中定义)。

当我加载以外的其他路由时,它的工作正常,但是AUTH正在加载两次(load_components函数)。

这是路线的示例。大多数页面都会有一个加载的组件,但是有一些不会。现在,LoadParent仅具有&lt; router-view /&gt; < /code>:

    // Simple page
    {
        path: "/home",
        name: "home",
        component: () => import("../loadPage.vue"),
    },
    // Pages with parent
    {
        name: 'auth',
        path: '/auth',
        meta: {
            title: "Some users" ,
            adminOnly: true
        },
        component: () => import("../loadParent.vue"),
        children: [
            {
                path: '',
                name: 'login',
                props: (route: any) => ({}),
                component: () => import("../loadPage.vue"),
            }
        ]
    }

因此,这是模板的样子:

<template>
    <component v-for="block in components" :is="{...block.component}" :key="Math.random()" :vars="block.props"></component>
</template>

在设置脚本中,我定义了ref ref ref存储的文件路径,例如:

const json: any = ref();

因为每个文件都定义为路由名称,所以我在设置中使用导入:

json.value = import('../pages/' + route.value + '.json');

所以这是我如何实际加载组件的功能:

const load_components = async () => {
        console.log('load page components ')
        // Get file for load
        Promise.resolve(json.value).then(function (e: any) {
            // Reset previous page pages
            components.value = [];

            // For each component for the page and register them under new const of the pages
            e.default.components.forEach((c: any) => {
                components.value.push({
                    "component": defineAsyncComponent(() => import('./templates/' + template.value + '/' + c.component)),
                    "props": c.props
                })
            })
        }).catch((e: any) => {
            // If component can't be loaded - Delete for production
            console.log(e + ' cannot be loaded!');
        });
    }

因此,为了触发函数,我正在做类似的事情:

onBeforeMount(async() => {
            json.value = import('../pages/' + route.value + '.json');

            // Initiate component load
            await load_components()
        })

        // /** Watch when client changes a page to load new json for next page - This function is for pages that has same component */
        watch(router, async (value: any) => {
            json.value = import('../pages/' + value.name + '.json');

            // There is no need for that if I load it really dynamically
            await load_components()
        })

也许只是方法不正确,您怎么看?

I'm trying to build Vue 3 dynamic loading JSON files, in order to create a website builder. So each page is defined as a JSON file, in order to allow the user to change the JSON file from the backend (all components are defined in that file).

When I'm loading every other route than auth, it's working fine, but Auth is loading twice (the load_components function).

Here is the example of the routes. Most of the pages will have a loadParent component, but there are a few that will not. And loadParent for now has only <router-view /> in it:

    // Simple page
    {
        path: "/home",
        name: "home",
        component: () => import("../loadPage.vue"),
    },
    // Pages with parent
    {
        name: 'auth',
        path: '/auth',
        meta: {
            title: "Some users" ,
            adminOnly: true
        },
        component: () => import("../loadParent.vue"),
        children: [
            {
                path: '',
                name: 'login',
                props: (route: any) => ({}),
                component: () => import("../loadPage.vue"),
            }
        ]
    }

So here is how template looks like:

<template>
    <component v-for="block in components" :is="{...block.component}" :key="Math.random()" :vars="block.props"></component>
</template>

And in the setup script I have defined ref where is stored path of the file, like:

const json: any = ref();

Because every file is defined as route name, I'm using import in setup:

json.value = import('../pages/' + route.value + '.json');

So here is how the function how I'm actually loading the components:

const load_components = async () => {
        console.log('load page components ')
        // Get file for load
        Promise.resolve(json.value).then(function (e: any) {
            // Reset previous page pages
            components.value = [];

            // For each component for the page and register them under new const of the pages
            e.default.components.forEach((c: any) => {
                components.value.push({
                    "component": defineAsyncComponent(() => import('./templates/' + template.value + '/' + c.component)),
                    "props": c.props
                })
            })
        }).catch((e: any) => {
            // If component can't be loaded - Delete for production
            console.log(e + ' cannot be loaded!');
        });
    }

So in order to trigger the function, I'm doing something like:

onBeforeMount(async() => {
            json.value = import('../pages/' + route.value + '.json');

            // Initiate component load
            await load_components()
        })

        // /** Watch when client changes a page to load new json for next page - This function is for pages that has same component */
        watch(router, async (value: any) => {
            json.value = import('../pages/' + value.name + '.json');

            // There is no need for that if I load it really dynamically
            await load_components()
        })

Maybe just the approach is not correct, what do you think?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文