Vue Router 4 in Vue 3 Applications
🎯 Introduction
By the end of this article, you will know how to use Vue Router 4 in a Vue 3 project. You will understand the main differences from Vue Router 3, create a router with createRouter, access routing information with useRoute and useRouter in <script setup>, and register navigation guards with the Composition API. If you already know routing in Vue 2, this will help you move to the Vue 3 ecosystem.
🛣️ What Is Vue Router 4?
Vue Router 4 is the official routing library for Vue 3. It succeeds version 3 and is built around Vue 3's reactivity system and application instance model.
The relationship between the versions is straightforward:
- Vue Router 3 → Vue 2 projects
- Vue Router 4 → Vue 3 projects
Both retain core concepts such as route configurations, <router-view>, and <router-link>, so most existing routing knowledge still applies. The main changes concern creating router instances, configuring history, installing the router at the application level, and accessing route objects with the Composition API.
⚙️ Installing and Creating a Router
Installing Vue Router 4
Install version 4.x of vue-router in your Vue 3 project:
npm install vue-router@4
Creating an Instance with createRouter
Vue Router 4 replaces new VueRouter() with the createRouter() factory function.
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
Configuring History
Vue Router 3 uses mode: 'history' or mode: 'hash' to select a mode. Vue Router 4 uses explicit history functions instead:
| Mode | Vue Router 3 | Vue Router 4 |
|---|---|---|
| hash | mode: 'hash' | createWebHashHistory() |
| history | mode: 'history' | createWebHistory() |
import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(),
routes,
});
createWebHistory() requires a server fallback configuration. Otherwise, refreshing a non-root route directly returns a 404. Vite handles this during development, but production deployments need appropriate server configuration.🔌 Installing the Router in a Vue 3 Application
Vue 3 creates an application with createApp and registers the router through app.use(router), instead of passing it to new Vue({ router }) as in Vue 2.
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
Routing is now available throughout the application, and components can access route information through either the Composition API or the Options API.
🧭 Routing in Components (Composition API)
In <script setup>, use the useRoute and useRouter composables instead of this.$route and this.$router.
Accessing the Current Route with useRoute
<template>
<div>
<p>User ID: {{ userId }}</p>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute();
const userId = computed(() => route.params.id);
</script>
Accessing the Router Instance with useRouter
<template>
<button @click="handleLogin">Log in and redirect</button>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
function handleLogin() {
// Login logic ...
router.push('/dashboard');
}
</script>
useRoute and useRouter in setup() or <script setup>. The router must be installed with app.use(router) for them to work.🛡️ Updated Navigation Guard Syntax
Navigation guards in Vue Router 4 follow the same general approach as Vue Router 3. Global guards support return values to control navigation, and in-component guards can be registered with the Composition API.
Global Before Guards
In Vue Router 4, beforeEach still supports next(), but can also control navigation through return values:
router.beforeEach((to, from) => {
const isLogin = Boolean(localStorage.getItem('token'));
// Redirect unauthenticated users to login when a page requires authorization
if (!isLogin && to.meta.requiresAuth) {
return '/login';
}
});
- Return
false: cancel navigation. - Return a route path or location object: redirect to that route.
- Return nothing or
undefined: continue navigation.
In-Component Guards with the Composition API
Vue Router 4 provides onBeforeRouteLeave and onBeforeRouteUpdate for use directly in <script setup>:
<script setup>
import { onBeforeRouteLeave } from 'vue-router';
onBeforeRouteLeave(() => {
const isSaved = confirm('Save before leaving this page?');
if (!isSaved) {
return false;
}
});
</script>
<script setup> or setup(), rather than in ordinary functions called outside that context.❓ Questions and Answers
Q1: What is the biggest difference between Vue Router 4 and Vue Router 3?
The main difference is creation and installation. Vue Router 4 uses createRouter() to create an instance and app.use(router) to install it in Vue 3. History is configured through functions such as createWebHistory().
Q2: How do you access current route parameters in <script setup>?
Call useRoute() to get the current route object, then read parameters from route.params, for example route.params.id.
Q3: What if refreshing a deployed route with createWebHistory() returns a 404?
HTML5 history mode requires a server fallback that serves index.html for application routes. Vite handles this in development; production servers such as Nginx or Apache need corresponding configuration.
🧪 Exercises
Exercise 1
Complete this Vue 3 router configuration using createRouter and createWebHistory, then install it in the application:
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
// Define a routes array containing / and /about here
const router = createRouter({
// Add history and routes here
});
export default router;
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
// Create the application instance and install the router
Exercise 2
Implement a button in <script setup> that navigates to /profile when clicked:
<template>
<button @click="goProfile">Go to profile</button>
</template>
<script setup>
// Import and use useRouter here
</script>
🎉 You now know the core skills for Vue Router 4 in Vue 3! You can create routes with createRouter, access routing through useRoute and useRouter in the Composition API, and control page access with navigation guards. Keep practicing to become comfortable with the Vue 3 ecosystem.
