How to install and set up Vue-router using npm
Prerequisite: Make sure you have setup a Vuejs project, if not yet, read on how to create one here.
At the root directory of your project, install vue router using npm by running this in your terminal
npm install vue-router@4
In your main.js
file, import the router and modules createRouter
and createWebHistory
import {createRouter, createWebHistory} from 'vue-router'
Create therouter
instance from createRouter
function which takes an object of history and routes options
const router = createRouter({history: createWebHistory(),routes: [] //provides routes options in an array
})
Inject our router
on the Vue instance to be used in all of our files, and pass the router as its argument. This will add the router to the full project, so we won’t need to add import
statement on each file/component
.use(router)
Here is full code for our main.js
import { createApp } from 'vue'
import {createRouter, createWebHistory} from 'vue-router'
import App from './App.vue'# Define some routes
const routes = []# Create the router instance and pass the `routes` options
const router = createRouter({# Provide the history implementation to use.
history: createWebHistory(),
routes, // short for `routes: routes`
})createApp(App)
.use(router)
.mount('#app')
After this installation and set-up, you can go ahead and create some routes