Introduction:
In order for particular pathways to render the related view, Vue Router links the browser’s URL/History and Vue’s components. When creating single-page apps, a vue router is utilized (SPA). When starting a new project, the vue-router may be configured by default.
Get Started:
Step 1: Set up your project.
After selecting the folder where you wish to launch your Vue project, type the following command into a terminal or command window.
vue create router
Using the command below, you may install Vue Router using Npm and the package vue-router.
vue add router
This will create a router folder with index.js file.
Step 2: Import router in your main.js file.
. . import router from './router' . . . new Vue({ router, . . .
Step 3: Add at least two components to test the routes.
Go to your components folder and add…
Home.vue
<template> <div> Home Component </div> </template> <script> export default { name: 'Home', } </script> <style scoped> </style>
About.vue
<template> <div> About </div> </template> <script> export default { name: 'About', } </script> <style scoped> </style>
Step 4: Add your components for the route.
Go to your router/index.js file and add the following code to it.
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../components/Home.vue' import About from '../components/About.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/About', name: 'About', component: About } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
Finally, run your code by npm run serve, and check the output!