Streamline Navigation Between Pages with Vue Router
Tags: vue, tutorial, webdev, frontend
Published: 2023-03-19 00:47:40

If you come from a React or Next.js background, you may find that handling page navigation in Vue.js is a bit tricky. To be honest, it took me a couple of hours to figure it out. In this blog post, I will show you how to handle page navigation in Vue.js.

The prerequisite for this project is simple: I won't style any components, so you need to do that yourself. I will only demonstrate page routing in Vue.

Without further ado, let's dive in.

## Step 1: Create a Vue project

If this is your first time working with Vue.js, you need to install Vue CLI before creating a project. Open your terminal (search for CMD or command and run as administrator) or use the terminal tab in your IDE.

Run this command: ``npm install -g @vue/cli``

Wait for it to install ** ``Vue CLI``** globally on your machine. 

When it's done, you can create a Vue project with this command: ``vue create project-name`` - replace "project-name" with what you want to name your project.

Follow the prompt commands and wait for it to help you bootstrap a Vue project.

When it's done, enter the project by running cd project-name and view your project by running vue serve.

Go to http://localhost:8080/ on your browser, and boom, you have a Vue project created.

## Step 2: Create components

Open your project with your chosen code editor by right-clicking on the project folder, then select "Open with," and choose a code editor. 

Alternatively, you can run ``code .`` in the terminal, and the project will be opened with your default code editor.

Creating a basic component in Vue is simple and straightforward. You can learn more about it yourself via [Vue documentation](https://vuejs.org) or tutorials on YouTube.

Check the project structure; you'll see a folder called "src," and create a "components" folder inside it.

Inside the components folder, create new files; each file will be used as a page: ``AboutMe.vue``, ``ContactMe.vue``, ``Homepage.vue``, etc.

**Your folder structure will look like this:**

![Vue Folder Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g6n6iuodoxhixuxhspgx.png)

Now, let's create a simple component for each page:

In Homepage.vue, paste this code:

```javascript
<template>   
  <h2>This is Homepage</h2>
  <p>I am homepage without style</p>
</template>

<script>
export default {
  name: "HomePage",
}
</script>

```

In about me:

```javascript
<template>   
  <h2>About Me</h2>
  <p>Learn more about me</p>
</template>

<script>
export default {
  name: "AboutPage",
}
</script>

```

You can handle other pages yourself; the next step is the big deal.

## Step 3: Create the Route.

We will deal with 3 different files here aside from your components; they are:

- App.vue
- main.js
- router.js

If you check your folder structure carefully, you will notice that ``App.vue`` and ``main.js`` have been created for you. Now let's create the third file ourselves.

The ``router.js`` will contain our routes. Before we can use Vue router, we need to install it. So go to your terminal again and run this command (ensure you're still inside the project folder):

``npm i vue-router@next`` OR ``yarn add vue-router@next``

This will install the vue-router for us. When it's done, create router.js in the root folder, or simply run this command ``touch router.js``.

We are going to configure our routes in this new file. Paste the following code there:

```javascript
import { createWebHistory, createRouter } from "vue-router" 
import HomePage from "./src/AppHome.vue"
import  AboutPage  from './src/components/AboutPage.vue';


const links = [
{
path: "/",     
name: "Home",     
component: HomePage,
},
{
path: "/about",     
name: "Home",     
component: AboutPage,
},


]


const router = createRouter({   
history: createWebHistory(),  
 routes: links, 
})  

export default router

```

Ensure you import your component correctly.

**Here is how the VUE's router.js configuration work in steps:**

**_Stage 1_**: Import "createWebHistory" and "createRoute" from the "vue-router" package that you just installed.

**_Stage 2_**: Define all your page links in an array. Create an object for each page (or link) containing ``"path"`` (which is also the link), ``"name"`` (to register the page), and ``"component"`` (which you are attaching to the link).

Note that if a path is set to ``"/"``, that will be the homepage of your project. And if you set ``"/about"`` as your path, you can access it via ``"localhost:8080/about"`` or ``"yourdomain.com/about"`` when deployed.

**_Stage 3_**: Create the router instance. Here, we are using ``"createWebHistory()"`` which creates an HTML5 memory and is commonly used for routing.

We also have ``"createWebHasHistory()"`` which will append ``"#"`` before your pathname, e.g., ``"/about"`` will become ``"localhost:8080/#/about"`` which is bad for [Search Engine Optimization, SEO](https://neilpatel.com/what-is-seo/).

We also have ``"createMemoryHistory()"`` which creates an in-memory-based history for navigating internally.

## Step 4: Connect routes with your app.

After configuring the router, the next step is to make this available in your app globally. 

To do this, find the ``"main.js"`` file in your project and replace anything you have there with this code:

```javascript
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './../router';


createApp(App).use(router).mount('#app')
```

Ensure that **"router"** is imported correctly, as a mistake here could cost you hours of troubleshooting.

**Now, let’s go to App.vue.**

This will serve as a placeholder for all your pages, and this component needs to keep track of changes in the route. 

Fortunately, we don't need to write any boring JavaScript code for this as Vue.js has done the heavy work for us.

Simply replace whatever is in the ``"App.vue"`` file with this:

```javascript
<template> 
 <div>   
<router-view />   
</div> 
</template>
```

Nothing much is happening here; the ``<router-view />`` tag tells Vue to mount or display the component associated with the current route in the browser.

Now, try going to the following:

- http://localhost:8080/ - You should see the homepage
- http://localhost:8080/about - You should see the about component

## Step 5: Link to different page internally

Everything is working, but not perfectly yet. If you want to link to another page in your project, you'll need to use the ``<router-link />`` tag provided by Vue-router instead of the ``<a href… />`` anchor tag.

For example, instead of ``<a href="/about">About</a>``, use ``<router-link to="/about">About</router-link>``.

## Conclusion: Handling Page Navigation in Vue.js

In conclusion, handling the route in Vue.js is not hard. If you follow the steps above correctly, you should be okay, and you can create a boilerplate for yourself in case you need to work with a multiple-page website in the future using Vue.

The tricky part of handling routes, either in React or Vue, is always "dynamic routing." I'll be writing about this next, so if you would like to be notified, kindly follow me.

If you found this helpful, don't forget to react and share it.

_> Cover Image credit: [Mapbox.com](https://www.mapbox.com)_