[英]Vue.js Router does not display correct child route
我遇到了 Vue.js 路由器的问题。 正如标题所示,这个问题是关于只显示父路由页面的子路由。 例如,您的帐户详细信息有一个路径www.example.com/account
。 然后,在您的帐户中,您可以看到不同的项目,这些项目将在www.example.com/account/project/foobar
路由中可用,其中project/foobar
是/account
的子路由,而foobar
是动态参数。 现在,当您 go 到一个项目时,您希望看到该项目,但您仍然看到帐户页面。
这是我遇到的问题。 我觉得一切都设置正确,但代码无论如何都显示在下面。
路由器.js
const routes = [
..., // other routes
{
path: '/account',
component: AccountPage,
meta: {
title: 'Your account'
},
children: [
{
path: 'project/:id',
component: ProjectPage,
props: true,
meta: {
title: 'Project'
}
}
]
}
];
const router = new VueRouter({
routes,
mode: 'history'
});
// Sets meta tags in the HEAD tag to, for example, change the title.
router.beforeEach((to, from, next) => {
const nearestWithTitle = to.matched.slice().reverse().find(r => r.meta && r.meta.title);
const nearestWithMeta = to.matched.slice().reverse().find(r => r.meta && r.meta.metaTags);
const previousNearestWithMeta = from.matched.slice().reverse().find(r => r.meta && r.meta.metaTags);
if(nearestWithTitle) document.title = nearestWithTitle.meta.title;
Array.from(document.querySelectorAll('[data-vue-router-controlled]')).map(el => el.parentNode.removeChild(el));
if(!nearestWithMeta) return next();
nearestWithMeta.meta.metaTags.map(tagDef => {
const tag = document.createElement('meta');
Object.keys(tagDef).forEach(key => {
tag.setAttribute(key, tagDef[key]);
});
tag.setAttribute('data-vue-router-controlled', '');
return tag;
})
.forEach(tag => document.head.appendChild(tag));
next();
});
我四倍检查了我是否使用了正确的组件,并且我 100% 确定我这样做了。 不过,它只是一直显示帐户页面而不是项目页面。 我确实注意到标题因更改元标记的代码而发生了变化,这意味着它知道下一页是项目页面。 我还检查了 function 参数包含的内容to
并很快发现这是它想要 go 到的项目路线,这完全有道理。
项目页面.vue
<template>
<transition name="project-anim">
<div>
Foo BAR
</div>
< /transition>
</template>
<script>
import MeineProject from '../../components/meine/project';
export default {
components: {
MeineProject
}
}
</script>
直接转到 URL (没有通过链接或任何东西的路线导航),也只显示帐户页面,所以我很确定这不是由于某种原因无法正常工作的过渡。 控制台中没有错误或警告。
我完全没有选择。 我希望你能帮助我。 谢谢你的时间: :)
帐户页面需要一个<router-view>
来呈现子路由。 如果您不希望项目页面呈现在帐户页面内,那么它不应该是帐户页面的子路由。
您可能需要这样的路由配置:
{
path: '/account',
component: AccountPage,
meta: {
title: 'Your account'
},
},
{
path: 'project/:id',
component: ProjectPage,
props: true,
meta: {
title: 'Project'
}
}
您可以将项目路由设置为/account/project/:id
但它不会是帐户路由的子路由,即使它以/account
为前缀。
由于父组件需要router-view
,因此您可以以这种方式保留子组件,并且每个子组件将呈现在完全不同的页面上:
{
path: '/account',
component: {
// render router-view into parent
render(c) {
return c('router-view');
}
},
children: [
{
path: '',
component: AccountPage,
meta: {
title: 'Your account'
},
{
path: 'project/:id',
component: ProjectPage,
props: true,
meta: {
title: 'Project'
},
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.