问题描述
项目中遇到了这样一个问题:我想要从父页面跳转到子页面,对应的路由设置为:
export const asyncRouterMap = {
/* 省略 */
{
path: '/about',
component: Layout,
redirect: '',
alwaysShow: true,
name: 'about',
meta: {
title: '侧边栏分类一',
breadNum: 1,
icon: 'nested',
},
children: [
{
path: 'fatherPage',
component: () => import('@/views/nested/menu1/fatherPage/index'),
name: 'fatherPage',
meta: {
title: '父页面',
breadNum: 2,
roles: ['admin', 'editor']
},
children: [
{
path: 'childPage1',
component: () => import('@/views/nested/menu1/fatherPage/children/childPageOne'),
name: 'childPage1',
meta: {
title: '子页面1',
breadNum: 2,
},
hidden: true
},
{
path: 'childPage2',
component: () => import ('@/views/nested/menu1/fatherPage/children/childPageTwo'),
name: 'childPage2',
meta: {
title: "子页面2",
breadNum: 2,
},
hidden: true
},
]
},
]
}
}
然后在父页面中通过router.push({ name: 'childPage1' })进行跳转,想要的结果是跳转后父路由区域替换为子路由,但是实际结果却是路径改变了,面包屑也更新了,控制台里也显示触发了子路由的mounted钩子里的方法,但是页面仍然是父页面没有替换为子页面。
原因分析
vue的路由显示是显示在<router-view />中的,并且要注意层级,如果存在这种层级: 父组件1 > 父组件2 > 子组件,那么,父组件2使用的<router-view />是父组件1的,而子组件使用的<router-view />是在父组件2之中的,所以如果父组件2中没有提供<router-view />,那么子组件可以加载却没法显示出来
解决方法
我们在父组件2中添加<router-view />,并通过在路由配置项的meta属性中设置属性来控制父组件页面是否显示
第一步: 更改路由配置
父组件2的meta中添加showFather: true,子组件的meta中添加showFather: false,更改后路由如下
export const asyncRouterMap = {
/* 省略 */
{
path: '/about',
component: Layout,
redirect: '',
alwaysShow: true,
name: 'about',
meta: {
title: '侧边栏分类一',
breadNum: 1,
icon: 'nested',
},
children: [
{
path: 'fatherPage',
component: () => import('@/views/nested/menu1/fatherPage/index'),
name: 'fatherPage',
meta: {
title: '父页面',
breadNum: 2,
showFather: true,
roles: ['admin', 'editor']
},
children: [
{
path: 'childPage1',
component: () => import('@/views/nested/menu1/fatherPage/children/childPageOne'),
name: 'childPage1',
meta: {
title: '子页面1',
showFather: false,
breadNum: 2,
},
hidden: true
},
{
path: 'childPage2',
component: () => import ('@/views/nested/menu1/fatherPage/children/childPageTwo'),
name: 'childPage2',
meta: {
title: "子页面2",
showFather: false,
breadNum: 2,
},
hidden: true
},
]
},
]
}
}
修改父组件,使用showFather控制是否显示父组件页面,并添加<router-view />用来显示其子组件
<template>
<div class="container">
<div v-show="$route.meta.showFather">
...
</div>
<router-view />
</div>
</template>
问题解决,可以正常使用了

在Vue项目中,从父页面通过router.push跳转到子页面时遇到问题,实际页面未替换。原因是子组件的<router-view/>未在父组件中定义。解决方案是,在父组件的meta中添加showFather属性为true,子组件设为false,并在父组件模板中使用v-show控制显示,同时添加<router-view/>以显示子组件。
1万+

被折叠的 条评论
为什么被折叠?



