Vue Router setup in Vue 3

Vue Router setup in Vue 3

Note: an option to add the Vue-router has now been integrate in Vite.

Previously, when creating a Vue project using the Vue CLI, the Vue Router could be installed easily by running vue add router. However, with Vue 3 and Vite, the router is installed manually. This can be done with NPM:

npm install vue-router@4

Once installed, the configuration of the router can be done by creating a dedicated .js file in the src directory of the app. To mimic the structure of Vue 2 projects, the router config file is named index.js, to be created in a folder called router, sub-folder of src. A basic content would look as follows:

import { createRouter, createWebHistory } from "vue-router";

import Home from '@/views/Home.vue'

const routes = [
    { path: '/', component: Home },

const router = createRouter({
    history: createWebHistory(),

export default router

Here, views are described in their .vue files in the views folder.

The router can then be added to the Vue application by editing the main.js file to look as follows:

// Components
import App from './App.vue'
import router from './router'

// Composables
import { createApp } from 'vue'

// Plugins
import { registerPlugins } from '@/plugins'

const app = createApp(App)



With this done, the Vue Router should now be ready to use in the application