Home > Back-end >  Multiple router views using vue router
Multiple router views using vue router

Time:07-18

Explanation: I have App.vue, Management.vue, Login.vue and Register.vue pages. And I have another folder saying management_pages. In that management folder I have Products.vue and Suppliers.vue files.

What I'm expecting to do: In the App.vue I want the router-view to be for Management.vue, Login.vue and Register.vue only. And when we go to my /management route I want the router-view to be Products.vue (/products) and Suppliers.vue (/suppliers) since the layout of both files are in my Management.vue file. How can I handle such thing?

I have tried this:

import { createRouter, createWebHistory } from "vue-router";
import Products from "../pages/Products.vue";
import Suppliers from "../pages/Suppliers.vue";
import ErrorPage from "../pages/ErrorPage.vue";
import Login from "../pages/Login.vue";


const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/products",
            name: "Products",
            component: Products,
        },
        {
            path: "/suppliers",
            name: "Suppliers",
            component: Suppliers,
        },
        {
            path: "/:pathMatch(.*)*",
            name: "ErrorPage",
            component: ErrorPage,
        },
        {
            path: "/login",
            name: "Login",
            component: Login,
        },
    ],
});

export default router;

CodePudding user response:

As stated in the comments, your question is vague, but since you are struggling I will try provide an answer. If I understand your question correctly, you want to define nested routes for /management/products and /management/suppliers.

First you need to add a <router-view></router-view> to your Management.vue component, where you want the content of Products.vue and Suppliers.vue.

Then you need to define the products and supplier routes as children of the management route, like:

routes: [
    {
         path: "/management",
         name: "Management",
         component: Management,
         children: [
            {
                 path: "products",
                 name: "Products",
                 component: Products,
             },
             {
                 path: "suppliers",
                 name: "Suppliers",
                 component: Suppliers,
              },
         ]
    },
    {
            path: "/login",
            name: "Login",
            component: Login,
    },
    {
            path: "/:pathMatch(.*)*",
            name: "ErrorPage",
            component: ErrorPage,
    },
],

Be sure to also import the Management.vue in your router file.

If you don't want /management to be a accessible route, you can define a redirect on the /management path to one of the children, like:

redirect: { name: 'Products' }

Hope this helps.

  • Related