VueJS - sub-nav components outside of router-view?

2019-08-16 18:16发布

问题:

I have a site layout using Bootstrap as follows (and it needs to stay like this):

<div class='row'>
  <div class='col-md-2'>
    <main-nav-component></main-nav-component>
    <sub-nav-component></sub-nav-component> <!-- Problem Area -->
  </div>

  <div class='col-md-10'>
    <router-view></router-view> <!-- MAIN CONTENT SECTION -->
  </div>
</div>

This gives me two columns across the whole site:

  • A navigation column on the left
  • A "contents" column on the right

Various pages (but not all) that are displayed in the main content section (via the router-view) also need to display their own sub-nav below the main nav. There are different sub-navs for different pages and I can't figure out how to accomplish this in VueJS. Any ideas?

回答1:

There's a couple ways of doing this. The easiest is to include the sub header nav components on the components themselves, but you said the above will not change, so instead, you need to pass some kind of data to the sub-nav-component to let it know what to render. One way you can do this is to use the route.

For example, in one application we needed to have a specific sub nav for a group of pages. We have declared a 'zone' in meta, then in the header component we read the zone and display the proper sub-nav for it.

In the router.js:

{
    path: '/profile/user',
    name: 'Profile',
    component: Profile,
    meta: { zone: 'profile'}
},

On the header component:

 computed: {
    zone(){
        return this.$store.state.route.meta.zone
    },

And in the html of the header component:

<profile-nav v-if="zone == 'profile'"></profile-nav>