Vue命名视图懒加载配置:子路由如何命中应用根层级router-view?
Vue路由子路由渲染根层级router-view问题解答
核心问题原因
子路由的component/components配置只能命中其父路由对应组件内部的<router-view>,无法直接命中应用根层级的<router-view>,这是Vue路由嵌套规则的默认设计:
- 你配置
/categories路由的组件为Categories,那它的所有子路由的组件,只会寻找Categories组件内部的<router-view>进行渲染,你没在Categories里写<router-view>自然不会渲染子路由组件 - 后续新增根层级的命名
router-view也不生效,就是因为子路由的配置无法向上跨层级匹配更上层的router-view
需求解决方案
如果你希望/categories和/categories/:slug都直接渲染在根层级的默认router-view,不需要嵌套展示Categories组件的内容,不需要配置为嵌套子路由,直接写为平级的顶级路由即可:
const routes = [ { path: "/categories", name: "categories", meta: { title: "Categories", }, component: lazyLoad("categories"), }, { path: "/categories/:slug", name: "product-list", meta: { title: "Categories", }, component: lazyLoad("product-list"), } ]
如果你确实需要保留嵌套路由结构(比如需要继承父路由的元信息、路由参数等),可以将父路由的组件改为仅渲染<router-view>的透明容器,不会额外展示其他内容,子路由组件就会正常渲染:
{ path: "/categories", name: "categories", meta: { title: "Categories", }, // 父路由仅作为路由层级容器,不渲染额外内容 component: { render: (h) => h('router-view') }, children: [ { path: "", name: "categories-index", component: lazyLoad("categories"), }, { path: ":slug", name: "product-list", meta: { title: "Categories", }, component: lazyLoad("product-list"), }, ], }
懒加载兼容问题
你写的命名视图结合懒加载的写法{ default: lazyLoad("product-list") }本身是完全合法的,Vue路由对命名视图的值没有限制,支持直接传入懒加载函数,只是之前的写法因为嵌套路由层级匹配问题没有渲染,写法本身没有错误。
内容的提问来源于stack exchange,提问作者r3plica
相关产品推荐
相关产品推荐

