Vue Router

Vue Routeropen in new window is a first-party Vue library and is the official router for Vue.js. Its purpose is to give developers the tools to quickly and easily build Single Page Applications.

Why Use Vue Router

Vue Router may not be necessary for simple web applications. But for larger applications or Single Page Applications (SPAs), it is an indispensable tool. Vue Router comes with many features that help with the development of SPAs, including:

  • Nested routes mapping
  • Dynamic routing
  • Route parameters, queries, and wildcards
  • Router history
  • Transition effects

Installing Vue Router

Vue Router is not included with the core Vue Framework and does require an additional npm command.

npm install vue-router@4

Adding Vue Router

Once installed, the library will need to be imported. If working with the Vite scaffold, the Vue Router library will be imported from the main.js file.

Two methods will be imported. First, the createRouter method will be used to create a new router instance. The createWebHashHistory method is used to set the history mode for the router. We will discuss history modes in more detail later in this module.

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

import { createRouter, createWebHashHistory } from 'vue-router'

createApp(App).mount('#app')