How to Use Vue Router?

Vue Router

How to use Vue Router In this tutorial we will see how to integrate and use vue- router in single page applications SPA

Vue Router – Tutorial

The first step would be to have nodejs installed on our computer or on a development server which has npm integrated to install packages, we proceed to install the corresponding package from a console

npm i -s vue-router

We add the flash -s to save the dependency to the package.json file, where it should show output like the following

"dependencies": {  
    "vue": "^2.6.11",
    "vue-router": "^3.3.4"

Once the package is installed we proceed to add the following lines of code in the main.js file

import Vue from 'vue'
import App from './App.vue'

import VueRouter from 'vue-router'

import { routes } from './routes';

Vue.config.productionTip = false


const router = new VueRouter({
	routes: routes,
	mode: 'history'    

new Vue({
  render: h => h(App),
  router: router

In the vue instance we will add the history mode to remove the # sign which is the default route that is added in single page SPA applications, among some of these technologies we have vuejs, reactjs, angular, so by removing the # we will work with friendly urls in the case of performing SEO positioning work

Now we create a file called routes.js, and add the following code

import Home from './components/Home/Home.vue'
import About from './components/About/About.vue'
import Contact from './components/Contact/Contact.vue'

export const routes = [
{ path: '', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }

It is necessary to create each component which will be associated with a route, an example of navigation would be to use the router-link function in the component that we want to use, where route navigation is applied

The vue framework is typically used to build front-end applications and is combined with back-end frameworks like laravel to consume services from a rest api when using libraries like axios