VUE路由器默认子路由最初未加载
本教程将介绍VUE路由器默认子路由最初未加载的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。
问题描述
我已经设置了一个简单的VUE(使用VUE-Router和Vuentify)项目,并且我正在尝试获取访问父路由时要加载的默认子路由。
我已尽最大努力按照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
如果您在沙箱中执行以下步骤,请问看到正在发生的情况:
在页面上,单击转到列表链接
在页上,单击转到节链接
加载页面时,我希望加载默认子路由(名为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 } }"
现在解析默认子路由。
这是意料之中的事吗?
我从这里获得信息,因此回答: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 } }"
,现在用户访问父路由器时会加载默认子路由。
希望这能在将来帮助其他人。
推荐答案
以下是我发现的有效方法:
...
{
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
}
]
}
...
添加redirect: { name: 'route.details' }
现在会使父路由重定向到选定的子路由。
好了关于VUE路由器默认子路由最初未加载的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。