In Vue.js, routing is typically handled using the official routing library called Vue Router. Vue Router allows you to build single-page applications with navigation between different views or components. Here's a step-by-step guide on how to handle routing in a Vue.js application:
Make sure to install Vue Router using npm or yarn:
bash# Using npm
npm install vue-router
# Using yarn
yarn add vue-router
javascriptimport Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
// Use VueRouter
Vue.use(VueRouter);
// Define your routes
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
// Add more routes as needed
];
// Create a router instance
const router = new VueRouter({
routes,
mode: 'history', // Use 'history' mode for cleaner URLs (requires server configuration)
});
// Create and mount the root instance
new Vue({
render: (h) => h(App),
router,
}).$mount('#app');
Create the components that correspond to your routes. For example, you might have Home.vue
and About.vue
.
Use the <router-link>
component to create navigation links in your components. For example:
vue<template> <div> <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> <router-view></router-view> </div> </template>
You can navigate programmatically in your components using $router.push
or $router.replace
. For example:
javascript// Inside a component method
methods: {
navigateToAbout() {
this.$router.push('/about');
},
},
You can use route parameters to create dynamic routes. For example:
javascriptconst routes = [
{ path: '/user/:id', component: User },
];
And in your component:
vue<template> <div> <p>User ID: {{ $route.params.id }}</p> </div> </template>
Vue Router provides navigation guards for additional control over navigation. You can use guards like beforeEach
, beforeResolve
, and afterEach
to perform actions before or after route changes.
This basic setup should get you started with routing in a Vue.js application. Adjust it according to your project's needs.