preface

Do Vue development without routing, especially in large and medium projects, pages and miscellaneous, in the configuration of routing will always become gradually irritable, because it takes time, and there is no much technical content, always feel that it is a waste of time.

In addition, if you take over other people’s projects, when business changes, or test feedback bugs. Usually, it is necessary to find the configured route according to the page URL, and then compare the.vue file corresponding to the Component parameter, which is cumbersome and inefficient.

Is there a way to automatically generate routes according to the.vue file, and the path of the route is the folder path of the file, which not only saves the time of route configuration, but also improves the efficiency of locating the page file according to the URL.

After some searching, I did find it, which is the following two plug-ins:

  • vite-plugin-pages
  • vite-plugin-vue-layouts

use

The installation

The names of these two add-ons indicate that they are vite add-ons and only support Vue3, so I used my Fantastic template to test them out.

First, install the dependencies. Vue-router does not need to be installed because it comes with the template.

pnpm add vite-plugin-pages vite-plugin-vue-layouts -D
Copy the code

After installing the dependency, you need to configure it in vite.config.js. Since these two plug-ins have different functions, we will introduce how to use them one by one.

vite-plugin-pages

This is the core of this introduction, it can generate the corresponding route of the file system, thus saving the time to manually configure the route.

First add the following configuration to viet.config.js:

import Pages from 'vite-plugin-pages'

export default {
    plugins: [
        Pages({
            dirs: 'src/views'.// The directory where the route is generated
            exclude: ['**/components/*.vue']  // Excluded directories, that is, all.vue files in components directories are not routed}})]Copy the code

For now, these two parameters are enough, and more parameters can be found in the viet-plugin-Pages project page.

Then you can import it into the page and use it.

import { createRouter } from 'vue-router'
import routes from '~pages'

const router = createRouter({
    // ...
    routes
})
Copy the code

Yes, it’s as simple as that, but there are also some advanced uses. For example, how to configure the route that passes parameters through Params?

In viet-plugin-pages, there is a special way to write []. For example, SRC /views/example/[id]. Vue generates path /example/:id.

For 404 pages, you can create a file SRC /views/[…all].vue, which generates the route /:all(.*)*.

In addition, we can add a
code block to the.vue file, which accepts jSON5 route configuration by default. Note that if path and name are configured in
, the automatically generated path and name will be overwritten.

<route>
{
    path: '/xxx/yyy',
    name: 'zzz',
    meta: {
        title: 'test page'
    }
}
</route>

<template>
	<div>
        This is a test page.
    </div>
</template>
Copy the code

There seems to be something missing at this time, right, that is the nesting. All the routes automatically generated through viet-plugin-Pages are level-1 routes. In actual project development, we will use nested features with
components to achieve some layout effects.

This is the time to introduce the following plug-in

vite-plugin-vue-layouts

First, configure it under vite.config.js:

import Pages from 'vite-plugin-pages'
import Layouts from 'vite-plugin-vue-layouts'

export default {
    plugins: [
        Pages({
            dirs: 'src/views'.// The directory where the route is generated
            exclude: ['**/components/*.vue']  // All.vue files in the components directory will not generate routes
        }),
        Layouts({
            layoutsDirs: 'src/layout'.// Directory for storing layout files
            defaultLayout: 'index'  // Default layout, SRC /layout/index.vue}})]Copy the code

See the viet-plugin-VuE-layouts project page for more configuration parameters.

Again, once configured, you can use it directly.

import { createRouter } from 'vue-router'
import { setupLayouts } from 'virtual:generated-layouts'
import generatedRoutes from 'virtual:generated-pages'

const routes = setupLayouts(generatedRoutes)

const router = createRouter({
    // ...
    routes
})
Copy the code

The only thing this plugin does is to process the level 1 routes generated by viet-plugin-Pages into nested routes, which looks something like this:

// {path: '/login', Component: () => import('/ SRC /views/login.vue'), name: 'login'} '/login', component: () => import('/src/layout/index.vue'), children: [ { path: '', component: () => import('/src/views/login.vue'), name: 'login' } ] }Copy the code

If you have multiple layouts, you can set them in


:

<route>
{
    meta: {
        layout: 'other'
    }
}
</route>
Copy the code

We can even make some magic changes. For example, some routes in the project need to use the layout page, and some do not need to use the layout page. Then we can set the unnecessary page to Layout: false:

<route>
{
    meta: {
        layout: false
    }
}
</route>
Copy the code

Also use the following code in the routing file:

import { createRouter } from 'vue-router'
import { setupLayouts } from 'virtual:generated-layouts'
import generatedRoutes from 'virtual:generated-pages'

let routes = []
generatedRoutes.forEach(v= >{ routes.push(v? .meta? .layout ! =false ? setupLayouts([v])[0] : v)
})

const router = createRouter({
    // ...
    routes
})
Copy the code

conclusion

Let’s summarize it with this picture:

│ ├─ ├─ ├─ ├─ vue │ ├─ params │ ├─ [id].vue /example/params/: Id │ ├─ Anti-Flag │ ├─ Cookie Example - cookies │ └ ─ svgicon. Vue/example/svgicon example - svgicon ├ ─ [...] all vue / : all (. *) * all ├ ─ index. The vue/index └ ─ login.vue /login loginCopy the code
  • To use route parameters, pass the[]Wrap the parameter name and set it to a filename
  • Folders do not generate routes; for example, the Example folder does not/examplerouting
  • The route name is automatically generated based on the directory structure of the file-Join to ensure that the name is unique
  • All components directories do not generate routes

Non-alcoholic drinks

I have integrated such a good feature into the Fantastic-admin background framework I developed for the first time. If you are interested, please click me to learn how to use it in detail.