Preface
When developing a backend management system, sometimes the backend will return to different menu lists according to permissions, and the frontend needs to obtain data asynchronously and then generate routing configurations in real time.
In the vue3 project, we use pinia and vue-router to implement dynamic routing. The key steps are as follows:
- Asynchronous request to obtain routing interface data;
- pinia state management saves routing information;
- vue-router implements routing configuration;
- Dynamically add routes.
1 Asynchronous request to obtain routing interface data
// /src/api/ export const getRouteList = () => { // Simulate asynchronous requests return new Promise((resolve) => { setTimeout(() => { resolve([ { name: "home", path: "/home", meta: { title: "front page" }, }, { name: "user", path: "/user", meta: { title: "user" }, }, ]) }, 1000) }) }
2 pinia state management saves routing information
// /src/store/ import { defineStore } from "pinia" export const useRouteStore = defineStore("route", { state: () => ({ routeList: ("routeList") ? (("routeList")) : [], isUpdate: false, }), actions: { updateRouteList(routeList) { = routeList ("routeList", (routeList)) = true }, }, getters: {}, })
3 vue-router implements routing configuration
import { createRouter, createWebHashHistory } from "vue-router" // Define the basic routing configurationconst routes = [ { path: "/:pathMatch(.*)", meta: { title: "404" }, name: "404", component: () => import("@/views/error/"), }, { path: "/login", name: "login", component: () => import("@/views/login/"), meta: { title: "Log in" }, }, { path: "/", name: "layout", component: () => import("@/views/layout/"), redirect: "/home", children: [], // There is no subroutine at the beginning }, ] export const router = createRouter({ history: createWebHashHistory(.BASE_URL), routes, }) //Route guard, used to handle the logic before routing jump(async (to, from, next) => { // Determine whether you are logged in and there is no token. Redirect to the login page if you are not logged in const token = ("token") if ( !== "/login" && !token) { return next({ name: "login" }) } next() })
4 Dynamically add routes
Core code
("layout", { path: , name: , component: () => import(`@/views/${}/`), })
Complete code
// /src/router/ import { createRouter, createWebHashHistory } from "vue-router" import { useRouteStore } from "@/store/route" import { getRouteList } from "@/api/route" // Define the basic routing configurationconst routes = [ { path: "/:pathMatch(.*)", meta: { title: "404" }, name: "404", component: () => import("@/views/error/"), }, { path: "/login", name: "login", component: () => import("@/views/login/"), meta: { title: "Log in" }, }, { path: "/", name: "layout", component: () => import("@/views/layout/"), redirect: "/home", children: [], // There is no subroutine at the beginning }, ] export const router = createRouter({ history: createWebHashHistory(.BASE_URL), routes, }) // Add dynamic routingconst addRoute = () => { const routeStore = useRouteStore() if () { ((item) => { if (!()) { ("layout", { path: , name: , component: () => import(`@/views/${}/`), }) } }) = false } } // Initialize the routingexport const initRouter = async () => { let routeList = ("routeList") ? (("routeList")) : await getRouteList() const routeStore = useRouteStore() (routeList) addRoute() } //Route guard, used to handle the logic before routing jump(async (to, from, next) => { // Add dynamic routing addRoute() // Determine whether you are logged in and there is no token. Redirect to the login page if you are not logged in const token = ("token") if ( !== "/login" && !token) { return next({ name: "login" }) } next() })
Note: After dynamically adding routes, refreshing the page will jump to the 404 page, because before entering the route guard, the program has already made a route matching, but the result is that nothing matches.
Solution: Call the initRouter function to initialize the route before router registration.
// import "./assets/css/" import { createApp } from "vue" import { createPinia } from "pinia" import App from "./" import { initRouter, router } from "./router" const app = createApp(App) const call = async () => { (createPinia()) await initRouter() (router) ("#app") } call()
This is the article about vue3 dynamic routing to solve the problem of blank or jumping 404 in refresh page. For more related vue3 refresh page blank or 404 content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!