'Conditional Dynamic Routing in Vue

I am trying to build an e-comm type vue app. One that has seperate sets of routes for "buyers" and "seller". I am struggling with using dynamic routes to add routes.

Scenerio:


A user opens the app which mounts the 1 Home.vue component for the path: '/' routes. In the onMounted() hook or a naviation guard, an api call is made to get the user (if previously logged in). If there is no user, the guard redirects to login. if there is a user, the user is stored and a role which can be either buyer, seller, or admin is retrieved from the user.

These are the fixed routes

import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import Signup from '@/views/Signup.vue'

const routes = [
  { path: '/', name: 'Home', component: () => import('@/views/Home.vue') },
  { path: '/login', name: 'Login', component: Login, children: [
    { path: 'test', name: 'test', component: () => import('@/views/seller/category.vue')}
  ] },
  { path: '/signup', name: 'Signup', component: Signup }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


export default router

The plan was to use the user's role to dynamically get the appropiate set of routes using the method below and the users role and then add them as nested routes to the path: '/', name: 'Home' route.

const roleRoutes = {
  buyer: [
    { name: "Dashboard", path: "", component: () => import("@/views/buyer/dashboard.vue") },
    { name: "Category", path: "cate-b", component: () => import("@/views/buyer/catergory.vue") },
  ],
  seller: [
    { name: "Dashboard", path: "", component: () => import("@/views/seller/dashboard.vue") },
    { name: "Category", path: "cate-s", component: () => import("@/views/seller/category.vue") },
  ],
};

const getRolePerRoute = (role) => {
  if(!role){
    return []
  }
  return roleRoutes[role]
}

export default getRolePerRoute

This is the Home.vue

<template>
  Home
  <router-view />
</template>

<script>
import { getRolePerRoute } from "@/router/routeHelper";
import { onMounted } from "@vue/runtime-core";
import { useRouter } from 'vue-router';
export default {
  setup() {
    const router = useRouter()

    onMounted(async () => {
      const res = await fetch("http://localhost:3000/user");
      let data = await res.json();
      if(data.user === true){
        let routes = getRolePerRoute(data.role)
        routes.forEach(route => {
          router.addRoute('Home', route)
        });
        router.replace(router.currentRoute.value.fullPath)
        console.log(router.getRoutes())
      }
    });
  },
};
</script>

<style></style>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source