Vue3.0 routing automatic import method example

Vue3.0 routing automatic import method example

1. Prerequisites

We use the require.context method to import. If we use it in a project created by vite, an error "require not found" will be reported, so we must use webpack to create a project. Or someone can tell me how Vite can solve this problem.

II. Rules

The rule we use is to search all directories and subdirectories under the src/views/ path, search for files named "index.vue", and use the name of the parent directory as the component name for registration. The structure is as follows:

Like public component registration, we only register the index.vue component, and components with other names are not registered.

3. Import

// src/router/index.ts

import {createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw} from 'vue-router'
import store from "@/store";
import daxie from "@/util/upper"; // Introduce a method to capitalize the first letter of a string. I am used to capitalizing the first letter of pathname. // Automatic routing registration const routerList:any = []
const requireComponent = require.context('@/views', true, /index.vue$/) // Find all files under the views path const dynamic_route = requireComponent.keys().filter(fileName => {
    return true
})
// Now the file array is out of order. We first sort it, with the parent route in front. If the child route is in front and the parent route has not been created, an error will be reported. // console.log(dynamic_route,"Before sorting")
dynamic_route.sort(function (a,b):number{
    const jieguoa:any = a.split("").filter((item:string)=>{
        return "/" == item
    })
    const jieguob:any = b.split("").filter((item:string)=>{
        return "/" == item
    })
    if (jieguoa.length<jieguob.length){return -1}
    if(jieguoa.length>jieguob.length){return 1}
    return 0
})

// console.log(dynamic_route,"after sorting")


dynamic_route.forEach(fileName => {
    const path = fileName.replace(".", "")
    const namelist = fileName.replace(".", "").replace("index.vue", "").split("/").filter((i:any) => {
        return i
    })
    // Test configuration const componentConfig = requireComponent(fileName)
    // The component can add any attribute at will. Currently, a canshu attribute is added, which is an array that stores the required dynamic parameters. // console.log(componentConfig.default,"Component Configuration 2")
    // Each layer needs to be specified manually, so just do three layers if (namelist.length == 1) {
        routerList.push({
            path:"/"+ namelist[namelist.length - 1],
            name: daxie(namelist[namelist.length-1]),
            component:()=>import(`../views${path}`),
            children:[],
        })
    }else if(namelist.length == 2){
        routerList.forEach((item:any)=>{
            if(item.name == daxie(namelist[0])){
                // Determine whether the component requires parameters const canshu = componentConfig.default.canshu || []
                if(canshu){
                    for (let i=0;i<canshu.length;i++){
                        canshu[i] = "/:"+canshu[i]
                    }
                    item.children.push({
                        path: namelist[namelist.length-1] + canshu.join(""),
                        name: daxie(namelist[namelist.length-1]),
                        component:()=>import(`../views${path}`),
                        children:[],
                    })
                }else{
                    item.children.push({
                        path: namelist[namelist.length-1],
                        name: daxie(namelist[namelist.length-1]),
                        component:()=>import(`../views${path}`),
                        children:[],
                    })
                }
            }
        })
    }else if(namelist.length == 3){
        routerList.forEach((item:any)=>{
            if(item.name == daxie(namelist[0])){
                item.children.forEach((yuansu:any)=>{
                    if (yuansu.name == daxie(namelist[1])){
                        // Determine whether the parameter is required const canshu = componentConfig.default.canshu || []
                        if(canshu){
                            for (let i=0;i<canshu.length;i++){
                                canshu[i] = "/:"+canshu[i]
                            }
                            yuansu.children.push({
                                path: namelist[namelist.length - 1]+canshu.join(""),
                                name: daxie(namelist[namelist.length-1]),
                                component:()=>import(`../views${path}`),
                            })
                        }else {
                            yuansu.children.push({
                                path: namelist[namelist.length - 1],
                                name: daxie(namelist[namelist.length-1]),
                                component:()=>import(`../views${path}`),
                            })
                        }
                    }
                })
            }
        })
    }
})
const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'Home',
        component: ()=>import("@/views/shouye/shouye.vue")
    },
    {
        path: '/about',
        name: 'About',
        component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
    },
    ...routerList,
    {
        path: '/404',
        name: '404',
        component: () => import('@/views/404.vue')
    },
    {
        path: '/:pathMatch(.*)',
        redirect: '/404'
    },
]
// Pay attention to the order. According to the latest routing matching rules, the 404 page must be at the end.
console.log(routes,"View the routing table content")

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

export default router

In this way, you only need to create components according to the rules, and they will be automatically registered in the route. Eliminate the tedious operation of manual registration.

Summarize

This is the end of this article about vue3.0 route automatic import. For more relevant vue3.0 route automatic import content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue3.0 CLI - 3.2 Routing Basic Tutorial
  • Vue2/vue3 routing permission management method example
  • A simple example of using Vue3 routing VueRouter4

<<:  mysql server is running with the --skip-grant-tables option

>>:  mysql5.7.17.msi installation graphic tutorial

Recommend

Detailed explanation of MySQL index selection and optimization

Table of contents Index Model B+Tree Index select...

Simple steps to write custom instructions in Vue3.0

Preface Vue provides a wealth of built-in directi...

Vue custom encapsulated button component

The custom encapsulation code of the vue button c...

hr horizontal line style example code

Copy code The code is as follows: <hr style=&q...

Detailed explanation of the use of MySQL Online DDL

Table of contents text LOCK parameter ALGORITHM p...

Introduction to user management under Linux system

Table of contents 1. The significance of users an...

Execute initialization sql when docker mysql starts

1. Pull the Mysql image docker pull mysql:5.7 2. ...

A more elegant error handling method in JavaScript async await

Table of contents background Why error handling? ...

How to solve the synchronization delay caused by MySQL DDL

Table of contents Preface Solution Tool Introduct...

Linux uses if to determine whether a directory exists.

How to use if in Linux to determine whether a dir...