深度嵌套路由和不同组件渲染,基于路由路径

Deep nested routes and different components rendering, based on route path

我的 routes.js 文件中有深层嵌套路由。正如您在下面的代码中看到的,我必须根据路线渲染不同的组件(如果路线是产品,我需要渲染 Products.vue 组件,但如果路线更深,我需要渲染 EmptyRouterView.vue 组件,其中包含模板 <router-view></router-view> 这样我就可以渲染子路由组件了)。

{
    path: '/products',
    name: 'products',
    component: {
        render(c) {
            if (this.$route.name === 'products') {
                return c(require('pages/Products/Products.vue').default)
            } else {
                return c(require('components/EmptyRouterView.vue').default);
            }
        }
    },
    meta: {
        requiresAuth: true,
        allowedPositions: '*'
    },
    children: [
        // Scan product to get info
        {
            path: '/products/search-product',
            name: 'search-product',
            component: () => import('pages/Products/SearchProduct.vue'),
            meta: {
                requiresAuth: true,
                allowedPositions:   '*'
            }
        },
        ....
    ]
}

我想知道是否有一些更短或更好的方法来做到这一点?例如(我知道我不能在箭头函数中调用它)是这样的吗?

component: () => {
    this.$route.name === 'products' ? require('pages/Products/Products.vue').default : require('components/EmptyRouterView.vue').default
}

或者你看看是否有可能以完全不同的方式做到这一点?

如果您需要任何其他信息,请告诉我,我会提供。谢谢!

您可以即创建另一个 .vue 文件并在其中包含两个组件 (<cmp-1 /> & <cmp2 />)。然后你可以用另一个 template-tag:

在模板中构建你的 if-statement
<template v-if="boolean">
<cmp-1 />
</template>
<template v-else>
<cmp-2 />
</template>

如果取决于你的路线。