Vue嵌套路由子组件不显示排查:访问子路由无组件加载
问题诊断与修复方案
我一眼就揪出了几个导致子组件无法加载的核心问题:
1. 子路由配置的拼写错误
你在父路由里把children写成了chilren(少了一个字母d)!Vue Router完全识别不了这个错误的属性,等于你的子路由配置根本没生效,自然加载不到Locations和Map组件。
2. 子路由的路径写法错误
子路由的path不该用绝对路径(带/开头),父路由已经定义了/profile/:username的前缀,子路由应该用相对路径——Vue Router会自动把父路由路径和子路由相对路径拼接起来。你现在写的/profile/:username/locations会被当成独立的顶级路由,根本不会关联到Profile的<router-view>,所以访问时不会渲染子组件。
3. 不影响加载的小笔误(顺便修正)
Map组件的模板里<p>标签内容写的是"Location",应该改成"Map",不然显示内容会混淆。
修正后的路由配置
import Home from './components/Home.vue'; import Profile from './components/Profile.vue'; import Map from './components/Map.vue'; import Locations from './components/Locations.vue' export const routes = [ { path: '', component: Home, name: 'Home'}, { path: '/profile/:username', component: Profile, name: 'Profile', children: [ // 修正拼写:chilren → children { path: 'locations', component: Locations, name: 'Locations'}, // 去掉开头的/,改用相对路径 { path: 'map', component: Map, name: 'Map'} // 同样使用相对路径 ]}, ];
修正后的Map组件模板
<template> <div class="wrapper"> <p>Map</p> <!-- 修正显示内容 --> </div> </template>
现在访问/profile/admin/locations或者/profile/admin/map,子组件应该就能正常渲染到Profile的<router-view>里了!
内容的提问来源于stack exchange,提问作者Onyx
相关产品推荐
相关产品推荐

