2

I'm pretty new to Vue and I just can't find a good way how to use nested components alongside with vue-router.

What I have so far (some not-important code omitted):

index.html

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

app.js

const router = new VueRouter({
    routes: [{ path: '/login', component: Login }]
})

const app = new Vue({
    router,
}).$mount('#app')

components/Login.vue

<template>
    <h1>Please log in</h1>
</template>

This works perfectly well - I navigate to /login and it shows me the message in h1 tag. If I create more components, like Register or ResetPassword and add them to the router, it still works well. But the problem is that there is some repeating code in those components (for example, I want all the auth-related pages to have blue background) so I'd like to somehow create a "parent" component, that would define stuff that is same for all the "children" components. Something like:

Auth component (makes the page-background blue)
    -> Login component (shows the login form)
    -> Register component (shows the registration form)

I know I can do this through route's "children":

const router = new VueRouter({
    routes: [
        { path: '/', component: Auth, children: [
            { path: '/login', component: Login }
            { path: '/register', component: Register }
        ]}
    ]
})

But with this configuration, there is the main route path: '/', which is completely wrong - I don't want it here - I don't want the Auth component to be used "standalone" - I want it just as a "wrapper" for the nested components.

What is the best way to solve this problem?

1 Answer 1

1

The way I've solved this issue is to use a base path redirect.

{ path: '', redirect: '/to/path' },

in your case it would be

const router = new VueRouter({
    routes: [
        {
            path: '/',
            component: Auth,
            children: [
                { path: '', redirect: '/login' },
                { path: '/login', component: Login },
                { path: '/register', component: Register }
            ]
        }
    ]
})

This ensures that

Sign up to request clarification or add additional context in comments.

1 Comment

What if I want to nest another view as a child of register component? With same approach it shows white screen for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.