No More Posting New Topics!

If you have a question or an issue, please start a thread in our Github Discussions Forum.
This forum is closed for new threads/ topics.

Navigation

    Quasar Framework

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search

    [How to] load all files in a directory as views

    Show & Tell
    3
    3
    1830
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • benoitranque
      benoitranque last edited by

      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 in src/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!

      1 Reply Last reply Reply Quote 4
      • bruce
        bruce last edited by

        Hello @benoitranque,
        The ‘@’ doesn’t compile for my Quasar 0.13 setup, I replaced with ‘components’
        This is great!
        Thank you

        1 Reply Last reply Reply Quote 0
        • rstoenescu
          rstoenescu Admin last edited by

          @bruce Thought I should drop this note: @ is a custom webpack alias in the v0.14 template which points to ‘components’.

          1 Reply Last reply Reply Quote 1
          • First post
            Last post