JAVASCRIPT

Setting up Client-Side Routing with Vue Router 4

Learn to configure and use Vue Router 4 to enable client-side routing in your Vue 3 single-page applications, creating dynamic navigation.

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import AboutView from '../views/AboutView.vue';

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView,
  },
  {
    path: '/user/:id',
    name: 'user',
    component: () => import('../views/UserView.vue'), // Lazy-loaded component
    props: true, // Pass route params as props
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

createApp(App).use(router).mount('#app');

// App.vue
<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link> |
    <router-link :to="{ name: 'user', params: { id: 123 }}">User 123</router-link>
  </nav>
  <router-view />
</template>

// views/UserView.vue
<script setup>
defineProps({
  id: { type: [String, Number], required: true },
});
</script>
<template>
  <div>
    <h1>User Profile: {{ id }}</h1>
  </div>
</template>
How it works: Vue Router is the standard library for client-side routing in Vue applications. This snippet shows how to define routes, create a router instance using `createWebHistory` for clean URLs, and integrate it into your Vue application via `app.use(router)`. In `App.vue`, `<router-link>` components create navigation links, and `<router-view>` acts as a placeholder where the matched component for the current route will be rendered. It also demonstrates how to lazy-load components and pass route parameters as component props.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs