Solutions to configuring 404 routing and lazy loading in Vue3
- In Vue 3 applications, handling unfound routes (i.e., 404 pages) is a basic but important task, especially in large applications, which ensures that users still have a good experience when trying to access non-existent paths.
- This article will guide you on how to configure 404 routing in Vue 3 and further optimize performance using lazy loading technology.
1. Configure 404 routing
// router/ import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'; import NotFound from '@/views/404/'; // Direct import, non-lazy loading example const routes: Array<RouteRecordRaw> = [ { path: "/:pathMatch(.*)*", redirect:'/404', }, { path: "/404", name: "NotFound", component: () => import("@/views/404/"), }, ]; const router = createRouter({ // Configure history mode history: createWebHashHistory(), routes, }); export default router;
2. Test
- Finally, test your 404 page configuration.
- Try to access some non-existent URLs to confirm that the 404 page can be displayed correctly and that the lazy loading function is working properly.
3. Error writing
- In Vue Router, each routing record must haveThe only one
name
property。 - When you define multiple ones with the same
name
Vue Router throws an error when routing because it cannot determine which route should be used when navigation. -
name
The main purpose isrouter-link
In the component or call()
、()
When using the method, it is used as the identifier of the target route.
Record the pitfalls of the development process:
{ path: "/:pathMatch(.*)*", name: "NotFound", redirect: "/404", }, { path: "/404", name: "NotFound", component: () => import("@/views/404/"), },
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.