【发布时间】:2020-03-18 10:15:45
【问题描述】:
我遇到了 Vue.js 路由器的问题。正如标题所示,这个问题是关于只显示父路由页面的子路由。例如,您的帐户详细信息有一个路径www.example.com/account。然后,在您的帐户中,您可以看到不同的项目,这些项目将通过路由www.example.com/account/project/foobar 提供,其中project/foobar 是/account 的子路由,foobar 是动态参数。现在,当您进入某个项目时,您希望看到该项目,但您仍然会看到帐户页面。
这是我遇到的问题。我觉得一切都设置正确,但代码还是如下所示。
router.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% 确定我这样做了。不过,它只是一直显示帐户页面而不是项目页面。我确实注意到标题因更改元标记的代码而发生了变化,这意味着它知道下一页是项目页面。我还检查了函数参数to包含的内容,很快就发现这是它想要去的项目路线,这完全有道理。
ProjectPage.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>? -
我主要有一个
App.vue。你需要给孩子单独的吗?如果是这样的话,我猜我不应该把它作为子路由,因为我想去一个完全不同的页面。 -
您已经回答了您的问题 :) 是的,如果您不希望项目页面呈现在帐户页面内,那么它不应该是帐户页面的子路由。
-
好东西!如果你愿意,你可以发布一个答案,我会接受的。
标签: javascript vue.js routing vue-router