VueJs - 如何在某些路线上隐藏全局组件(例如导航栏)? [英] VueJs - How to hide global component (e.g navbar) on some routes?

查看:52
本文介绍了VueJs - 如何在某些路线上隐藏全局组件(例如导航栏)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我的 vuejs SPA 上的绝大多数视图在顶部都有一个导航栏组件.但是,某些选择视图(例如登录)不应显示此内容.

So the vast majority of views on my vuejs SPA have a navbar component at the top. However, some select views such as the login should not display this.

我的解决方法是导入导航栏并在需要时单独添加到每个视图中,但现在我可以看到它在从一个视图转到另一个视图时会导致奇怪的闪烁 - 大概是因为导航栏组件正在被删除,并且立即重新添加.这似乎是错误的.

My workaround was to import the navbar and add to each view individually if it was needed, but now I can see it causes a weird flickering when going from one view to another - presumably because the navbar component is being removed, and immediately re-added. This seems wrong.

我假设有一些方法可以在 App.vue 中添加导航栏组件,但有条件地使用 vue-router 在某些路由上隐藏它?这方面的最佳做法是什么?

I assume there's some way to add the navbar component in App.vue but conditionally hide it on some routes with vue-router? What's the best practice for this?

推荐答案

一种常用的方法是使用嵌套路由.这是我的一个项目中的一个示例:

A common way is to use nested routes. Here is an example from one of my projects:

const router = new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        {
            path: '/login',
            name: 'login',
            component: LoginView,
        },
        {
            path: '/admin',
            name: 'admin',
            component: AdminShell,
            children: [
                {
                    path: 'home',
                    name: 'admin_home',
                    component: AdminHomeView
                },
            ]
        },
    ],
});

主视图将只有一个路由器视图组件,因此可以在没有导航栏的情况下显示登录视图组件.

The main view will just have a router-view component, so the login view component can be displayed without the navbar.

<!-- App -->
<v-app>
    <v-content>
        <router-view> </router-view>
    </v-content>
</v-app>

管理 shell 将被注入到主视图中,它将包含导航栏、侧边栏和它需要的任何其他内容.

The admin shell will be injected into the main view, and it will contain the navbar, side bar and what ever else it needs.

<!-- Admin shell -->
<v-container fill-height>
    <v-toolbar color="blue darken-3" dark app :clipped-left="$vuetify.breakpoint.mdAndUp" fixed>
        <v-toolbar-title style="width: 300px" class="ml-0 pl-3">
            <v-toolbar-side-icon @click.stop="drawer = !drawer"></v-toolbar-side-icon>
            <span class="hidden-sm-and-down">Admin</span>
        </v-toolbar-title>
        <v-spacer></v-spacer>
        <UserInfo></UserInfo>
    </v-toolbar>

    <!-- Nested route -->
    <router-view></router-view>
</v-container>

然后,AdminHomeView 将被注入到管理 shell 视图的嵌套路由器视图中.

Then, the AdminHomeView will be injected into nested router-view of the admin shell view.

这篇关于VueJs - 如何在某些路线上隐藏全局组件(例如导航栏)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆