我想知道如何最好地在Vue.js中设置路由器来处理“子页面”。例如,我有一个导航条,它可以路由到不同的页面。在其中一个页面中,我希望有指向子页面的链接。我该怎么安排呢?
到目前为止,我已经这样做了:
App.js
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
</div>
</template>,然后我设置了路由器:
export default new Router({
routes: [
{
path: "/",
name: "home",
component: Home
},
{
path: "/about",
name: "about",
component: About,
children: [
{
path: "/child1",
name: "child1",
component: Child1
}
]
}
]
})和my About.vue提供到Child1的链接
<template>
<div class="about">
<h1>This is an about page</h1>
<router-link to="/child1">Child1</router-link>
<router-view></router-view>
</div>
</template>和我的孩子们1.vue
<template>
<div class="child1">
<p>My message</p>
</div>
</template>我的问题是,指向Child1的链接同时显示在About页面和Child1页面上。我只想在有关页面上显示它,而只想在Child1页面上显示来自Child1页面的内容。
设置这样的东西的最佳实践是什么?
谢谢
发布于 2019-02-28 10:52:10
我的问题是,指向Child1的链接同时显示在About页面和Child1页面上。我只想把它显示在“关于”页面上
只是为了澄清这里发生了什么:即使子路由是活动的,但当子路由处于活动状态时,到Child1的链接总是可以在About组件中可见。
Way 1
当没有匹配路由时(即当没有子路由处于活动状态时),您可以向<router-view>提供回退内容。这将是一个展示链接的好机会。
<template>
<div class="about">
<h1>This is an about page</h1>
<router-view>
<router-link to="/child1">Child1</router-link>
</router-view>
</div>
</template>Way 2
如果模板更复杂,如果希望将链接放置在模板的其他位置,则上述解决方案可能无法工作。
因此,您必须使用v-if手动控制链接的可见性,以便只有在子路由不活动时才能看到链接。
<template>
<div class="about">
<h1>This is an about page</h1>
<!-- Show only when no child routes are active -->
<router-link v-if="$route.name === 'about'" to="/child1">Child1</router-link>
<!-- Or, do not show when Child1 route is active -->
<router-link v-if="$route.name !== 'child1'" to="/child1">Child1</router-link>
<router-view></router-view>
</div>
</template>https://stackoverflow.com/questions/54923395
复制相似问题