DEV Community

loading...
Cover image for Routers in Vue JS

Routers in Vue JS

Yağmur
computer science student, loves to write
・2 min read

Hi there! I'm learning Vue and one of the best practice is sharing what you learn. So here i am with routers. Let's go!

Why we use routers?

Let's think about you are on a web page. Whenever you click at a link or etc page will be directed to a new page. But there are two ways to do this logic.

First one which is traditional one is multi page application. Everytime we send a request for a page we wanted.

The second which is called single page application logic is that once load all pages and play with the links. So everything done in user browsers. That will make our website faster.

Since Vue is a SPA this is explaination of why we use routers.

Let's move the code now. Let's create a folder and with manual selection choose router options with vue 3.

vue create routers-vue
Enter fullscreen mode Exit fullscreen mode

Let's look at the router folder which has index.js

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routers = [{
  path:'/',
  name:'Home',
  component: Home
}
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

export default router
Enter fullscreen mode Exit fullscreen mode

We import createRouter and createWebHistory from node-modules.
We have an array called routers that will be contain pages.
Finally we import the router so in the main.js we can use.

How we define inside routers array?

path -> which is the direction
name - > when we define custom navigations, we can use name instead of paths. so if path change in the future, we don't need to modify everything.
component -> we can define component in two way. above we can see the first option. let's see the second one. Don't forget to create an about page.

  {
        path: '/about',
        name: 'About',
        component: function() {
            return import ('../views/About.vue')
        },

    }
Enter fullscreen mode Exit fullscreen mode

Let's add two buttons to App.vue In the template we see router-view and router-link which are special to vue router.

With router-link we can navigate to an another page.

<template>
  <div id="nav">
    <router-link :to="{name:'Home'}">Home</router-link> |
    <router-link :to="{name: 'About'}">About</router-link>
  </div>
  <router-view/>
</template>
Enter fullscreen mode Exit fullscreen mode

Previously we said we can use name instead of path. This is an example of usage.

If we use path-way:

<router-link to="/Home"> Home </router-link>

You can see ":" which is a v-bind. V-bind is a way to we change the value with bounding data. we usually use with html attribute.

Next post I'll explain nested dynamic routers, redirect and 404 Pages.

Discussion (0)