Miraculously, this Vue background framework doesn't need to manually configure routing

Posted by Jade on Fri, 04 Mar 2022 12:17:28 +0100

preface

Vue development is inseparable from routing, especially for medium-sized and large-scale projects. There are many and miscellaneous pages. When configuring routing, it will always become increasingly irritable, because it is time-consuming and does not have much technical content. I always feel that it is a waste of time.

In addition, if you take over someone else's project, when the business changes or there are bug s in the test feedback. Generally, you need to find the route corresponding to the configuration according to the page URL, and then compare the route corresponding to the {component} parameter vue# files are cumbersome and inefficient.

Is there a way to base it on The vue file automatically generates a route, and the path of the route is the path of the folder where the file is located, 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 really found the following two plug-ins:

use

install

It can be seen from the names of these two plug-ins that they are vite plug-ins and only support Vue3, so I'll move out of mine Fantastic-template The project template has been tested.

Install dependencies first. Because the template comes with Vue router, it does not need to be installed.

pnpm add vite-plugin-pages vite-plugin-vue-layouts -D

After installing the dependency, you need to install it in # vite config. JS. Because these two plug-ins have different functions, let's introduce how to use them one by one.

vite-plugin-pages

This is the core of this introduction. It can generate the corresponding route from the file system, so as to save the time of manually configuring the route.

First, at # vite config. JS: add the following configuration:

import Pages from 'vite-plugin-pages'

export default {
    plugins: [
        Pages({
            dirs: 'src/views',  // File directory where routing needs to be generated
            exclude: ['**/components/*.vue']  // Excluded directories, i.e. the directories under all components directories are not included vue file generation route
        })
    ]
}

At present, only these two parameters need to be configured, and there are more parameters to configure vite-plugin-pages Project page.

Then you can use it by introducing it in the page.

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

const router = createRouter({
    // ...
    routes
})

Yes, it's that simple. Of course, there are some high-order usages. For example, how to configure the route passing parameters through params?

A special writing method is provided in vite plugin pages, which is []. For example, Src / views / example / [ID] Vue , this file, and the final generated route , path , is / example/:id.

For 404 pages, we can create such a file as Src / views / [... All] Vue, the route it generates is /: all(. *) *.

In addition, we can also Add < route > < / route > code block in vue file, which receives the route configuration in "json5" format by default. It should be noted that if "path" and "name" are configured in < route > < / route >, 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>

At this time, there seems to be something wrong. Yes, nested routing. The routes automatically generated through vite plugin pages are primary routes. In the actual project development, we will use the characteristics of nested routing and match < router View > < / router View > components to achieve some layout effects.

At this time, we will introduce the following plug-in

vite-plugin-vue-layouts

First, at # vite config. JS modify the following configuration:

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

export default {
    plugins: [
        Pages({
            dirs: 'src/views',  // File directory where routing needs to be generated
            exclude: ['**/components/*.vue']  // The excluded directories are those under all components directories vue files do not generate routes
        }),
        Layouts({
            layoutsDirs: 'src/layout',  // Layout file storage directory
            defaultLayout: 'index'  // Default layout, corresponding to Src / layout / index vue
        })
    ]
}

For more configuration parameters, please see vite-plugin-vue-layouts Project page.

The same is true. After configuration, it can be used 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
})

The plug-in only does one thing, which is to process the primary route generated through vite plugin pages into nested routes, which is roughly as follows:

// Before treatment
{
    path: '/login',
    component: () => import('/src/views/login.vue'),
    name: 'login'
}

// After treatment
{
    path: '/login',
    component: () => import('/src/layout/index.vue'),
    children: [
        {
            path: '',
            component: () => import('/src/views/login.vue'),
            name: 'login'
        }
    ]
}

If you have multiple layouts, you can set them in < route > < route >:

<route>
{
    meta: {
        layout: 'other'
    }
}
</route>

Some magic changes can even be made. For example, some routes in the project need to use layout pages, while others do not. Then we can set the unnecessary pages to "layout: false":

<route>
{
    meta: {
        layout: false
    }
}
</route>

At the same time, 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
})

The summary is based on the following figure:

  • To use routing parameters, you need to wrap the parameter name with [] and set it as the file name
  • Folders do not generate routes. For example, the example folder does not generate / example # routes
  • The route name will be automatically generated according to the directory structure of the file and connected with - to ensure the uniqueness of the name
  • No route will be generated for all components directories

 

Topics: Java Front-end