Patryk Gołębiowski
Patryk Gołębiowski

Reputation: 57

I cannot have similar router paths in Vue3

I'm just learning Vue3 and trying to do some routing, but I'm getting an error message that makes no sense. Maybe it's related to some kind of nested routing, but I also tried to do children and it didn't want to work.

This works:

import { createRouter, createWebHistory } from 'vue-router';
import HomePage from '../home/HomePage.vue';
import FetchAccount from '../nonPrimaryADAccounts/FetchAccount.vue';
import CreateADAccount from '../nonPrimaryADAccounts/CreateADAccount.vue';

export default createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: HomePage,
    },
    {
      path: '/FetchAccount',
      name: 'FetchAccount',
      component: FetchAccount,
    },
    {
      path: '/CreateADAccount',
      name: 'CreateADAccount',
      component: CreateADAccount,
    },
  ],
});

And this does not:

import { createRouter, createWebHistory } from 'vue-router';
import HomePage from '../home/HomePage.vue';
import FetchAccount from '../nonPrimaryADAccounts/FetchAccount.vue';
import CreateADAccount from '../nonPrimaryADAccounts/CreateADAccount.vue';

export default createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: HomePage,
    },
    {
      path: '/NonPrimaryADAccount/FetchAccount',
      name: 'FetchAccount',
      component: FetchAccount,
    },
    {
      path: '/NonPrimaryADAccount/CreateADAccount',
      name: 'CreateADAccount',
      component: CreateADAccount,
    },
  ],
});

Error message:

4:29  error  Unable to resolve path to module '../nonPrimaryADAccounts/CreateADAccount.vue'  import/no-unresolved

Upvotes: 2

Views: 415

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23500

If you need nested path the recommended approach is to use a function to generate the routes with the prefix:

const withPrefix = (prefix, routes) => 
    routes.map( (route) => {
        route.path = prefix + route.path;
        return route;
    });

export default createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: HomePage,
    },
    ...withPrefix('/NonPrimaryADAccount',[
        { 
          path: '/FetchData',
          name: 'FetchData',
          component: FetchData,
        },
        { 
          path: '/CreateADAccount',
          name: 'CreateADAccount',
          component: CreateADAccount,
        },
    ]),
]

Upvotes: 1

Related Questions