[How to] load all files in a directory as views
-
Hello
This script will allow you to load all files in a directory as views. This allows you to avoid registering all views manually, rather you configure once then simply start adding pages!
// router.js // returns all vue files in directory 'page' const pages = require.context('./components/page', true, /^\.\/.*\.vue$/) .keys() .filter(page => page.split('/').length >= 2) .map(page => page.slice(2).slice(0, -4)) // Standard quasar load function. Only load view once needed function load (component) { // '@' is aliased to src/components return () => System.import(`@/${component}.vue`) } // page loading function function loadPage (page) { return { path: `/${page}`, component: load(`page/${page}`) } } // Add first route with layout let routes = [ { path: '/', component: load('Layout'), children: [] } ] // Add all other pages pages.forEach(page => { routes[0].children.push(loadPage(page)) }) // Standard quasar default will redirect to '/404' route // Always leave this last one routes.push({ path: '*', redirect: '/404' }) // Not found
You are all set! With this any
.vue
file you add insrc/components/page/
will be added as a view.Of course this has limitations. Your files names must not have spaces. If anyone is interested I could show you how to extract a title for your page from the filename.
Have a nice day!
-
Hello @benoitranque,
The ‘@’ doesn’t compile for my Quasar 0.13 setup, I replaced with ‘components’
This is great!
Thank you -
@bruce Thought I should drop this note:
@
is a custom webpack alias in the v0.14 template which points to ‘components’.