【问题标题】:Load Vue's parent component and all nested routes lazily懒加载Vue的父组件和所有嵌套路由
【发布时间】:2023-04-03 10:56:01
【问题描述】:

我在延迟加载嵌套路由时遇到问题!

这是我的父路线:

import ChildRoutes from "app/modules/child.route”;

routes: [
    {
        path: '/child',
        component: resolve => require(['app/modules/root'], resolve),
        children: ChildRoutes
    }
]

而我的child.route.js

import ChildHome from …
import ChildContact from …

export default [
    {
        path: '',
        name: 'childHome',
        component: ChildHome
    },
    {
        path: 'about',
        name: 'childAbout',
        // doesn’t work
        component: resolve => require(['./components/about.vue'], resolve)
    },
    {
        path: 'contact',
        name: 'childContact',
        // this one doesn’t work as well
        component: ChildContact
    },
    ...
]

当然,第一个子路由 (childHome) 会自动工作,但之后我只会得到没有渲染组件的空白页面! 如果我懒加载父母和孩子,一切都会好起来的!

我做错了什么?

值得一提的是,我的项目使用 vue 2.0vue-routervuex 和 SSR

【问题讨论】:

  • 任何控制台错误?
  • 没什么贝尔明!一个干净的控制台,正如我所说,没有组件呈现到页面中

标签: lazy-loading vue.js vue-router vuex


【解决方案1】:

我正在研究两个明显的问题。

首先,看起来您的代码在调用 require() 而不是 import() 方面与 vue-router 文档有所不同。

看这里

您的 child.route.js 文件的改进版本是

import ChildHome from "";
import ChildContact from "";

export default [
    {
        path: '',
        name: 'childHome',
        component: ChildHome
    },
    {
        path: 'about',
        name: 'childAbout',
        component: () => import("./components/about.vue")
    },
    {
        path: 'contact',
        name: 'childContact',
        component: ChildContact
    },
]

这有可能解决您可能遇到的任何延迟加载问题。也有可能是无关紧要的,如果是这样,请继续阅读。


第二个问题,/child 路由有一点难题,vue-router 对这类东西很挑剔。你的父路由文件有一个 /child 路由的组件:

    path: '/child',
    component: resolve => require(['app/modules/root'], resolve),

那么你的子路由文件也有这个路由的组件:

    path: '',
    name: 'childHome',
    component: ChildHome

在这种情况下,孩子'' 路由与来自孩子的/child 相同。当为一个路由加载两个组件时,Vue 很可能会感到困惑。清除这一点,您的问题就会消失。

【讨论】:

    【解决方案2】:

    父路由

    import ChildRoutes from "app/modules/child.route”;
    routes: [
        ...ChildRoutes,
    ]
    

    child.route.js

    export default [ 
        {
            path: '/child',
            component: () => import ('@/app/modules/root'), <-- Just verify this path,
            children: ...
        }
    ]
    

    【讨论】:

    • 你的回答有什么意义?用动态导入替换require?!不,这不会解决问题。在这两种情况下,结果对我来说都是一样的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 2021-12-09
    • 2021-11-15
    • 2016-12-19
    • 2016-06-08
    • 2021-10-19
    相关资源
    最近更新 更多