Skip to content

Instantly share code, notes, and snippets.

@chrfs
Last active February 5, 2018 10:02
Show Gist options
  • Save chrfs/bd9e21e57c42c321c4dc49304a4395f4 to your computer and use it in GitHub Desktop.
Save chrfs/bd9e21e57c42c321c4dc49304a4395f4 to your computer and use it in GitHub Desktop.
Dynamic generated and required routes with Vue-Router
import VueRouter from 'vue-router';
import config from './example-config';
// Please notice that every Vue-Component is exporting a meta object with a title in my instance:
// exports default {};
// exports meta {
// title: 'example',
// ...
// };
// generate routes
const routes = config.reduce(
(arrBefore, vRoute) =>
arrBefore.concat(
vRoute.vueComponents.map((vueComponent, vueComponentIndex) => ({
name: require(`../${vRoute.filepath.join('/')}/${vueComponent}.vue`).meta.title,
component: require(`../components/${vueComponent}.vue`).default,
path: (`/${vRoute.routePrefix.join('/')}/${vueComponent}`).toLowerCase()
}))
),
[]
);
// set alias for the first route
routes[0].alias = '/';
// initialize VueRouter
const router = new VueRouter({
routes
});
// export default for the main application
export default router;
// only in the config mentioned component names are required, no need for importing before creating the routes
// ***resulted output of my gist would be equal to***
// import VueRouter from 'vue-router';
// import config from './config';
// import Shoes from '../components/categories/Shoes.vue';
// import Clothes from '../components/categories/Clothes.vue';
// import Tops from '../components/categories/clothes/Tops.vue';
// import Clothes from '../components/categories/clothes/Shirts.vue';
// const routes = [
// {
// name: 'Shoes',
// component: Shoes,
// path: '/categories/shoes',
// alias: '/'
// },
// {
// name: 'Clothes',
// component: Clothes,
// path: '/categories/clothes'
// },
// {
// name: 'Tops',
// component: Tops,
// path: '/categories/clothes/tops'
// },
// {
// name: 'Shirts',
// component: Shirts,
// path: '/categories/clothes/shrits'
// }
// ];
// const router = new VueRouter({
// routes
// });
// export default router;
const componentTypes = {
SHOES: "Shoes",
CLOTHES: "Clothes",
TOPS: "Tops",
SHIRTS: "Shirts"
};
// only below mentioned components are required, no need for importing before creating the route
const config = [
{
filepath: ['components', 'categories'],
vueComponents: [componentTypes.SHOES, componentTypes.CLOTHES],
routePrefix: ['categories']
},
{
filepath: ['components', componentTypes.CLOTHES],
vueComponents: [componentTypes.TOPS, componentTypes.SHIRTS],
routePrefix: ['categories', componentTypes.CLOTHES]
}
];
export default config;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment