英文:
Conditional container for vue-router named view?
问题
在路由视图的父组件中(即包含<router-view name='...'>
标签的组件)是否可以检测到命名视图是否已设置?
用例:我有一个导航抽屉,其内容根据路由而变化,但前导和附加抽屉插槽内容始终相同。但是对于某些页面,没有导航抽屉内容,在这种情况下,我不想渲染导航抽屉。例如,组件模板如下所示:
<template>
<system-bar></system-bar>
<v-navigation-drawer
v-bind='navDrawerProps'
>
<template v-slot:prepend>
<v-list-item @click='rail = !rail' prepend-icon="mdi-menu"></v-list-item>
<v-divider></v-divider>
</template>
<template v-slot:append>
<v-divider></v-divider>
<v-list-item>
<template v-if='model.connection?.token'>
<router-link to='/logout'><v-list-item prepend-icon="mdi-logout-variant">Logout</v-list-item></router-link>
</template>
<template v-else>
<v-list-item prepend-icon="mdi-login-variant" @click='login'>Login / Signup</v-list-item>
</template>
</v-list-item>
</template>
<router-view name="nav"></router-view>
</v-navigation-drawer>
<v-main app>
<router-view></router-view>
</v-main>
</template>
我希望为v-navigation-drawer
添加一个v-if
条件,类似于v-if=named-view-called-nav-is-defined
。
英文:
Is it possible to detect whether a named view is set in the router view parent component (i.e. the one containing the <router-view name='...'>
tag)?
Use case: I have a navigation-drawer who's content that varies depending on route, but the prepend and append drawer slot content is always the same. But for some pages there is no nav-drawer content and in such cases I don't want to render the nav-drawer at all. For example, the component template looks like:
<template>
<system-bar></system-bar>
<v-navigation-drawer
v-bind='navDrawerProps'
>
<template v-slot:prepend>
<v-list-item @click='rail = !rail' prepend-icon="mdi-menu"></v-list-item>
<v-divider></v-divider>
</template>
<template v-slot:append>
<v-divider></v-divider>
<v-list-item>
<template v-if='model.connection?.token'>
<router-link to='/logout'><v-list-item prepend-icon="mdi-logout-variant">Logout</v-list-item></router-link>
</template>
<template v-else>
<v-list-item prepend-icon="mdi-login-variant" @click='login'>Login / Signup</v-list-item>
</template>
</v-list-item>
</template>
<router-view name="nav"></router-view>
</v-navigation-drawer>
<v-main app>
<router-view></router-view>
</v-main>
</template>
I want a v-if
condition for the v-navigation-drawer
like v-if=named-view-called-nav-is-defined
.
答案1
得分: 1
找到解决方案。发现可以从$route.matched
访问命名路由。鉴于我定义了一个计算属性用于在v-if
中使用:
computed: {
hasNav() {
const components = this.$route.matched
.map((m) => m.components)
.reduce((a, b) => ({ ...a, ...b }), {});
return 'nav' in components;
}
},
英文:
Found solution. Figured out you can access named routes from $route.matched
. Given that I defined a computed prop to use in v-if
:
computed: {
hasNav() {
const components = this.$route.matched
.map((m: any) => m.components)
.reduce((a: any, b: any) => ({ ...a, ...b }), {});
return 'nav' in components;
}
},
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论