乐闻世界logo
搜索文章和话题

How to create a 404 component in vuejs using vue - router

1个答案

1

Creating a 404 component using vue-router in Vue.js is a common requirement to handle cases where users access non-existent pages. Here are the detailed steps to implement this functionality:

1. Install and Configure vue-router

First, ensure that vue-router is installed in your Vue project. If not installed, you can install it using npm or yarn:

bash
npm install vue-router # or yarn add vue-router

Next, set up the routes in your project. Create a router.js file (or add route configuration to an existing file).

2. Create the 404 Component

In the src/components directory, create a new Vue component named NotFound.vue. This component will display the 404 error page.

vue
<template> <div> <h1>404 Not Found</h1> <p>The page you are trying to access does not exist.</p> </div> </template> <script> export default { name: 'NotFound', }; </script> <style> /* Styles */ </style>

3. Configure Routes

In router.js, import the NotFound component and add a rule to handle non-existent routes in the Vue Router configuration.

javascript
import Vue from 'vue'; import Router from 'vue-router'; import Home from './components/Home.vue'; import NotFound from './components/NotFound.vue'; Vue.use(Router); export default new Router({ mode: 'history', routes: [ { path: '/', name: 'home', component: Home }, { path: '*', name: 'not-found', component: NotFound } ] });

Note that path: '*' is a wildcard route that matches paths not covered by other route definitions. Place this rule at the end of the route definitions to ensure it only triggers when no other route matches.

4. Use router-view

In your main Vue application template, use the <router-view></router-view> component to render the matched component. This is typically done in the App.vue file:

vue
<template> <div id="app"> <router-view></router-view> </div> </template>

5. Test the 404 Page

Start your Vue application and try accessing a non-existent route in the browser, such as http://localhost:8080/some-non-existing-page. You should see your 404 page displaying '404 Not Found' and 'The page you are trying to access does not exist.'

By following these steps, you can effectively manage and display 404 error pages in your Vue.js project, enhancing user experience.

2024年7月15日 17:54 回复

你的答案