【发布时间】:2019-08-24 07:54:27
【问题描述】:
我已经设置了一个简单的 Vue(带有 vue-router 和 Vuetify)项目,并且我试图在访问父路由时加载默认的子路由。
我已尽力按照 Vue 文档执行此操作,但默认子路由在我访问它的父路由时根本不会加载。
这是router.js文件中的代码:
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home'
import Details from './views/Details'
import List from './views/List'
import NotFound from './views/NotFound'
import Secondary from './views/Secondary'
import Sections from './views/Sections'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'route.home',
component: Home
},
{
path: '/list',
name: 'route.list',
component: List
},
{
props: true,
path: '/sections/:id',
name: 'route.sections',
component: Sections,
children: [
{
alias: '',
path: 'details',
name: 'route.details',
component: Details
},
{
path: 'secondary',
name: 'route.secondary',
component: Secondary
}
]
},
{
path: '*',
name: 'route.notfound',
component: NotFound
}
]
})
这里是 CodeSandbox.io 项目的链接: https://codesandbox.io/s/l41zk6olqz
如果您在沙盒中按照这些步骤操作,您会看到发生了什么:
- 在主页页面上,点击转到列表链接
- 在列表页面上,点击Go to Sections链接
- 当 Sections 页面加载时,我期待默认子路由(名为
route.details的加载),但是,它没有
如果您单击选项卡列表中的 详细信息 链接,详细信息 页面会加载。 我确定这是一个简单的错误,但我只见树木不见森林。
提前致谢。
更新(2019-04-03 @ 07:00):
一些进一步的挖掘,以下似乎工作:
router.js
...
{
props: true,
path: '/sections/:id',
// name: 'route.sections',
component: Sections,
children: [
{
alias: '',
path: 'details',
name: 'route.details',
component: Details
},
{
path: 'secondary',
name: 'route.secondary',
component: Secondary
}
]
}
...
然后将 router-link 从 :to="{ name: 'route.sections', params: { id: 1 } }" 更改为 :to="{ name: 'route.details', params: { id: 1 } }"
现在解析默认子路由。
这是预期的吗?
我从这个 SO 答案中得到了信息:https://stackoverflow.com/a/50065601/9127864
更新(2019-04-03 @ 07:28):
进一步挖掘表明这也是可能的:
router.js
...
{
props: true,
path: '/sections/:id',
name: 'route.sections',
component: Sections,
redirect: {
name: 'route.details'
},
children: [
{
alias: '',
path: 'details',
name: 'route.details',
component: Details
},
{
path: 'secondary',
name: 'route.secondary',
component: Secondary
}
]
}
...
然后我可以将router-link 改回:to="{ name: 'route.sections', params: { id: 1 } }",现在当用户访问父路由器时会加载默认子路由。
希望这将在未来对其他人有所帮助。
【问题讨论】:
标签: javascript vue.js vue-router