How can I create a subcomponent to use with vue router?

Viewed 330

First, I'm new to vue.js, so I apologize if my question is a bit basic. My App.vue is:

<template>
  <div id="app">
    <router-view />
  </div>
</template>

I have a router.js, which has:

import Vue from 'vue';
import Router from 'vue-router';

import Container from "./components/Container.vue";
import Home from "./components/Home.vue";
import Login from "./components/Login.vue";

Vue.use(Router);

export default new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [{
            path: '/',
            name: 'login',
            component: Login,
        },
        {
            path: '/home',
            name: 'home',
            component: Container,

        },
    ],
});

The idea is that Container has navigation, and should be used for various components (including Home). How can I do that?

1 Answers

Just like you have a App.vue containing router-view, you need a Container component to contain another router-view component. This will create a nested router views.

Once you do that, you will need to add children routes:

export default new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [{
            path: '/',
            name: 'login',
            component: Login,
        },
        {
            path: '/home',
            component: Container,
            children: [
                {
                    // LEAVE THIS PATH BLANK. Matches /home
                    path: '',
                    name: 'home',
                    component: HomeComponent,
                },
                {
                    path: 'another-route',
                    name: 'nested-route',
                    component: AnotherComponent,
                }
            ]
        },
    ],
});

The key is to add children routes and leave one of the children with a blank path.

Related