What is Automatic Routes

I know this concept comes from a NuxtJs feature: Automatic Routes.

When you normally use a VUE application with vue-Router, you have to set up a configuration file (router.js) and manually add all routes to it. Nuxt automatically generates the VUe-Router configuration for you based on the Vue files in the Pages directory that you provide. This means you never have to write router configurations again! Nuxt also provides automatic code splitting for all your routes.

Benefits of Automatic Routes

  • Fast development: Automatically generate routes by creating folders. In the meantime, there is no need to worry about routing bugs.

The example of Automatic Routes

Your project catalog is as follows:

SRC ├ ─ ─ views │ ├ ─ ─ index. The vue │ ├ ─ ─ the about the vue │ └ ─ ─ the user │ ├ ─ ─ the about the vue │ └ ─ ─ index. The vueCopy the code

Corresponding to automatically generated routes:

[{
  component: () => import('@/views/index.vue'),
  path: '/'
},
{
  component: () => import('@/views/about.vue'),
  path: '/about'
},
{
  component: () => import('@/views/user/index.vue'),
  path: '/user/'
},
{
  component: () => import('@/views/user/about.vue'),
  path: '/user/about'
}]
Copy the code

implementation

Implement environment

Vue3, VUE-CLI, vue-router

Implementation approach

  • You need a javascript API that reads the file path. Although we can’t use nodeJS ‘file API, webpack’s require.context () does the job.
  • Lazy load routes using import ().
  • Loop to get and modify the file path, add route

The implementation code

Find the router configuration file, such as/SRC /router/index.js. Modified as follows:

import { createRouter, createWebHashHistory } from 'vue-router';

// Automatically inject routes
const modules = require.context('.. /views'.true./.vue/);
const autoRoutes = modules.keys().map((item) = > {
  const viewName = item.slice(2);
  const path = item.slice(1).replace('.vue'.' ').replace('index'.' ');
  const viewModule = () = > import(`.. /views/${viewName}`);
  return {
    path,
    component: viewModule,
  };
});
const routes = autoRoutes;

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

export default router;
Copy the code

In this way, the effect of the above example can be achieved

More and more

This code simply demonstrates the implementation. You can add as much as you want.