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

MySQL 8.0.12 installation and configuration method graphic tutorial

Record the installation and configuration method ...

ie filter collection

IE gave us a headache in the early stages of deve...

Summary of practical skills commonly used in Vue projects

Table of contents Preface 1. Use $attrs and $list...

Lambda expression principles and examples

Lambda Expressions Lambda expressions, also known...

Detailed discussion on the issue of mysqldump data export

1. An error (1064) is reported when using mysqldu...

Detailed explanation of web page loading progress bar (recommended)

(When a web page is loading, sometimes there is t...

Examples of using the ES6 spread operator

Table of contents What are spread and rest operat...

Beginners learn some HTML tags (1)

Beginners can learn HTML by understanding some HT...

Detailed explanation of the difference between CSS link and @import

How to add css in html? There are three ways to s...

MySql sharing of null function usage

Functions about null in MySql IFNULL ISNULL NULLI...

Understand the implementation of Nginx location matching in one article

Since the team is separating the front-end and ba...

How to set up cross-domain access in IIS web.config

Requirement: The page needs to display an image, ...

Detailed explanation of the spacing problem between img tags

IMG tag basic analysis In HTML5, the img tag has ...