In this tutorial, we will be discussing how to handle undefined routes in vue-router 5 using the Composition API in Vue.js. Vue-router is the official router for Vue.js, which allows you to build single-page applications with Vue components.
When a user navigates to a route that is not defined in the router setup, vue-router will redirect to a 404 page by default. However, sometimes we may want to customize this behavior and show a different page or perform some other action instead. We can achieve this using the Composition API in Vue.js.
Here is a step-by-step guide on how to handle undefined routes in vue-router 5 with the Composition API:
- First, make sure you have Vue.js and vue-router 5 set up in your project. You can install them using npm or yarn by running the following commands:
npm install vue@next
npm install vue-router@next
- Create a new Vue instance and set up vue-router in your main.js (or equivalent) file:
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import NotFound from './components/NotFound.vue'
const routes = [
{ path: '/', component: Home },
]
const router = createRouter({
history: createWebHistory(),
routes,
})
const app = createApp(App)
app.use(router)
app.mount('#app')
- Create a NotFound component to display a custom 404 page. You can create a new file called NotFound.vue and define the component like this:
<template>
<div>
<h1>404 Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</div>
</template>
<script>
export default {
name: 'NotFound',
}
</script>
- Now, we will use the Composition API to handle undefined routes. In your main.js file, add the following code to define a catch-all route that redirects to the NotFound component:
router.resolve({
path: '/:pathMatch(.*)*',
}).resolved.matched[0].components.default = NotFound
- Test your application by navigating to a route that is not defined in your router setup. You should see the custom 404 page displayed instead of the default behavior of vue-router.
By following these steps, you can customize the handling of undefined routes in vue-router 5 using the Composition API in Vue.js. This allows you to provide a better user experience by displaying a custom 404 page or performing other actions when a user navigates to a route that does not exist. Happy coding!
좋은 강의 감사합니다.