How to install and set up Vue-router using npm


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


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`

After this installation and set-up, you can go ahead and create some routes


Post a Comment (0)
Previous Post Next Post