我在vue.js 2。
当我最初访问Localhost/列表时,它会正确加载index.vue和map.vue小时候。
当我使用路由器链接到localhost/listings/1,然后将路由器链接返回到localhost/listings时,它仍然加载show.vue模板。这不应该发生?
我没有导航警卫或任何应干扰的东西。无论如何是否有纠正?
我的路线:
window.router = new VueRouter({
routes: [
...
{
path: '/listings',
name: 'listing.index',
component: require('./components/listing/index.vue'),
children: [
{
path: '',
component: require('./components/listing/map.vue')
},
{
path: ':id',
name: 'listing.show',
component: require('./components/listing/show.vue')
}
]
},
...
]
});
如果您想要默认子路由,则不应命名"父"路由器,因此请使用 :to="{name: 'listing.index'}"
,使用默认子路由的名称(例如:to="{name: 'listing.map'}"
)。
代码应该像这样:
window.router = new VueRouter({
routes: [
...
{
path: '/listings',
component: require('./components/listing/index.vue'),
children: [
{
path: '',
name: 'listing.map'
component: require('./components/listing/map.vue')
},
{
path: ':id',
name: 'listing.show',
component: require('./components/listing/show.vue')
}
]
},
...
]
});
也许尝试重新安排孩子,路线是按照他们从上到下匹配的顺序,因此希望可以对其进行修复:
window.router = new VueRouter({
routes: [
...
{
path: '/listings',
name: 'listing.index',
component: require('./components/listing/index.vue'),
children: [
{
path: ':id',
name: 'listing.show',
component: require('./components/listing/show.vue')
}
{
path: '',
component: require('./components/listing/map.vue')
},
]
},
...
]
});
只是为了澄清一下,您的path: ''
本质上是"捕获全部",这可能是为什么当它在顶部立即被发现时,因此路由器永远不会传播到:id
路线。
在VUE 2.6.11中,如果命中父途径,您可以自动重定向到子路由:
const routes = [
{
name: 'parent',
path: '/',
component: Parent,
children: [
{
name: 'parent.child',
path: 'child',
component: Child,
}
],
/**
* @type {{name: string} | string} Target component to redirect to
*/
redirect: {
name: 'parent.child'
}
}
];
当您使用named routes
并且想在内部加载组件时,您必须为孩子使用名称路由。
在导航菜单链接中,如果您使用parent
的名称路由,即使儿童路径一无所有,孩子也不会自动加载。
假设我们有一个用户路由,我们想默认显示组件中的用户列表,因此,每当我们转到"/用户"路径时,我们都想在其中加载一个用户列表:
routes: [
{
path: '/user',
name: 'User',
component: User,
children: [
{path: '', name: 'UserList', component: UserList}, // <== child path is = '';
]
}
]
如果您考虑代码,则可以假设如果您使用名称"用户"来路由,则可能也会在其中获得用户列表,因为父母和孩子的路径都是相同的。但这不是,您必须选择"用户列表"作为名称。为什么会发生这种情况?因为VUEJS加载了您所指的确切组件,而不是URL。您实际上可以对此进行测试,而不是在链接中使用命名路由,您只能引用URL,这次Vuejs会毫无问题地加载父母和孩子,但是当您使用命名路由时,它不会查看URL并加载您所指的组件。