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

The perfect solution for highlighting keywords in HTML

I recently encountered a feature while working on...

Pure HTML and CSS to achieve JD carousel effect

The JD carousel was implemented using pure HTML a...

JavaScript uses canvas to draw coordinates and lines

This article shares the specific code of using ca...

Methods and steps for Etcd distributed deployment based on Docker

1. Environmental Preparation 1.1 Basic Environmen...

Some tips for writing high-performance HTML applications

How can you improve web page performance? Most de...

Overview and differences between html inline elements and html block-level elements

Block-level element features : •Always occupies a ...

iframe src assignment problem (server side)

I encountered this problem today. I reassigned the...

CentOS 7 builds hadoop 2.10 high availability (HA)

This article introduces how to build a high-avail...

Coexistence of python2 and python3 under centos7 system

The first step is to check the version number and...

Detailed description of the use of advanced configuration of Firewalld in Linux

IP masquerading and port forwarding Firewalld sup...

Detailed explanation of MySQL master-slave inconsistency and solutions

1. MySQL master-slave asynchrony 1.1 Network Dela...

Use Element+vue to implement start and end time limits

This article example shares the specific code for...

Using nginx + fastcgi to implement image recognition server

background A specific device is used to perform i...

Vue advanced usage tutorial dynamic components

Table of contents Basic description AST parsing R...