Home > Net >  Vue-router: Nested router-views in named router-views
Vue-router: Nested router-views in named router-views

Time:04-02

I want to pass in a component to a named router view. My components:

// Main.vue
<template>
  <div>
    <div >
      <router-view name="header"></router-view>
    </div>
    <div >
      <div >
        <router-view name="left-content"></router-view>
      </div>
      <div >
        <router-view name="right-content"></router-view>
      </div>
    </div>
    <div >
      <router-view name="footer"></router-view>
    </div>
  </div>
</template>

my other component

// Header.vue
<template>
  <div>
    <div >
      <router-view></router-view>
    </div>
    <div >
      <!-- content for button -->
    </div>
  </div>
</template>

my routes // Routes.js

const main = {
  path: "/",
  name: "main",
  component: Main,
  children: [{
    name: "children",
    path: "children",
    components: {
      header: Header,
      left: LeftComponent,
      right: RightComponent,
      footer: FooterComponent
    }
  }]
}

How can I inject a component in Header

my attempt is like this: I try to have a children to Header component, but it doesn't work

const main = {
  path: "/",
  name: "main",
  component: Main,
  children: [{
    name: "children",
    path: "children",
    components: {
      header: {
        path: '',
        component: Header,
        children: [{ path: "", component: A }]
      },
      left: LeftComponent,
      right: RightComponent,
      footer: FooterComponent
    }
  },
  {
    name: "children2",
    path: "children2",
    components: {
      header: {
        path: '',
        component: Header,
        children: [{ path: "", component: B }]
      },
      left: LeftComponent,
      right: RightComponent,
      footer: FooterComponent
    }
  }]
}

CodePudding user response:

See: Components Basics . Don't use router-view, use component itself:

<template>
  <div>
    <header />
    <left-content />
    <!-- ... -->
  </div>
</template>

<script>
import Header from './path/to/your/header/file'
import LeftContent from './path/to/your/leftContent/file'
// ...

export default {
  components: {
    Header,
    LeftContent,
    // ...
  }
}
</script>

Then, in component, for example in Header:

<template>
  <div >
    <div >
      <A v-if="isInFirstChildren" />
      <B v-else />
    </div>
    <div >
      <!-- content for button -->
    </div>
  </div>
</template>

<script>
import A from './path/to/file'
import B from './path/to/file'

export default {
  components: {
    A,
    B
  },
  computed: {
    isInFirstChildren () {
      return this.$route.name === 'children'
    }
  }
}
</script>
  • Related