What is Vue Router?
Vue Router is the authority switch for Vue.js (opens new window). It profoundly coordinates with Vue.js center to make building Single Page Applications with Vue.js a breeze.
Install Vue Router package:
npm i vue-router
When utilized with a module framework, you should expressly introduce the switch through Vue.use() :
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter)
Example:
Open main.js and add the following code in it:
import Vue from 'vue' import App from './App.vue' import VueRouter from 'vue-router' import Routes from './routes' Vue.use(VueRouter); const router=new VueRouter({ routes:Routes, mode:'history' }); new Vue({ el: '#app', render: h => h(App), router:router })
Open App.vue and add the following code in it:
<template> <div> <app-header></app-header> <router-view></router-view> </div> </template> <script> import Header from "./components/Header.vue"; export default { components: { "app-header": Header, }, };
Open router.js and add the following code in it:
import ShowBlogs from './components/ShowBlogs.vue'; import AddBlog from './components/AddBlog.vue'; export default[ {path:'/',component:ShowBlogs}, {path:'/add',component:AddBlog}, ]
Open Header.vue and add the following code in it:
<template> <nav> <ul> <li><router-link to="/" exact>Blog</router-link></li> <li><router-link to="/add" exact>Add a new blog</router-link></li> </ul> </nav> </template>
Code in action: