Friday, December 27, 2024

Navigating Success: Setting up Vue Router in your Project.

Programming LanguageNavigating Success: Setting up Vue Router in your Project.


Introduction
In the ever-growing tech space of today, a seamless navigation experience can either make or break your web application. That is why our journey begins with understanding Vue and the Vue router. 

What is Vue ?
Vue also pronounced as ‘view’, was created by Evan You. Vue is an open-source, Front-end, Javascript framework for building user interfaces and Single Page Applications(SPA). It builds an application on top of HTML, CSS and Javascript. 

What is a Vue Router ?
A vue router is the official router for vue.js. It is a guide that transforms a Single Page Application(SPA) into a dynamic multi-page application. It integrates with vue to make building a Single Page Applications(SPA) and navigating through it a walk in the park.

This story follows Chidinma, a passionate front-end developer, as she embarks on a mission to set up a vue router in her latest project.

The Challenge
Staring at the project requirements on my screen; a modern day application with multiple pages and dynamic navigation. The challenge was clear: to set up a single page application with a robust routing system to multiple pages. Without it, users would be lost , unable to explore the different sections of my application seamlessly.

Discovering the solution
In my quest for a solution, I came across the vue router, an official library for vue.js, designed to handle seamless navigation, as explained under the definition of a vue router. The promise of a clean, declarative routing, and the ability to handle nested routes was intriguing! I just knew that this was the key to unlocking the multi-page potential of my project. Now, let us delve into the key features of vue-router i discovered along the way.

What are the key features of the vue router?

There are some key features that vue-router has that makes it unique. These features are:

  1. Nested route mapping : vue-router allows for nested routes, which means you can have routes within routes.
  2. Dynamic routing: it allows you change your applications route on the fly.

  3. Component-based router configuration : it allows you structure your routes in a component-based manner. This makes routing configuration easier to manage as the application grows.

  4. Customizable scroll behavior : it lets you customize the scroll behavior of your application when navigating between routes.

  5. Navigation control :it gives you control over navigation, allowing you to programmatically navigate to different routes in response to user actions.

  6. Route params, Query and Wildcards : it supports route parameters, query parameters, and wildcards, giving you control over how your application responds to different URLs.

Now that we have an idea of what vue is, who founded it, what the vue-router is and some key features of the vue-router, we can now delve into setting up a vue-router in our project. 

Step by step implementation

The steps involved in setting up a vue-router in a project is:

  1. Folder/file structure: properly understanding the folder and file structure of our project is important . First, we have a diagrammatic representation of our file structure and secondly, we have an explanation of the structure.
my-vue-project/
├── node_modules/
├── public/
│   ├── favicon.ico
│   └── index.html
├── src/
│   ├── assets/
│   │   └── logo.png
│   ├── components/
│   │   └── HelloWorld.vue
│   ├── router/
│   │   └── index.js
│   ├── views/
│   │   ├── HomeView.vue
│   │   ├── AboutView.vue
│   │   └── NotFoundView.vue
│   ├── App.vue
│   ├── main.js
│   └── router
│       └── index.js
├── .gitignore
├── babel.config.js
├── jsconfig.json
├── package.json
├── README.md
└── vue.config.js
Enter fullscreen mode

Exit fullscreen mode

Explanation of the folder/file structure
A. Root Directory (my-vue-project/): it contain several folders(the forward-slash(/) indicates that it is a folder) and files, as explained below. 

  • node_modules/: Contains all the npm packages installed for the project.

  • public/: Contains static assets and the main HTML file (index.html).

  • src/: The source directory where all the Vue components, assets, and configuration files reside.

  • assets/: For static assets such as images, fonts, etc.

  • components/: Contains reusable Vue components.

  • router/: Contains the router configuration file (index.js).

  • views/: Contains Vue components that are used as views/pages in the application.

  • App.vue: The root Vue component.

  • main.js: The entry point of the application where Vue instance is created and mounted.

  • store/: (If using Vuex) Contains the Vuex store configuration for state management.

  • .gitignore: Specifies which files and directories should be ignored by Git.

  • babel.config.js: Babel configuration file.

  • jsconfig.json: JavaScript configuration file for the project.

  • package.json: Lists the project’s dependencies and scripts.

  • README.md: A markdown file providing information about the project.

  • vue.config.js: Optional configuration file for Vue CLI.

2.After creating a vue project(my-vue-project),understanding its folder and file structure. We then install the vue-router using npm, and set up the vue-router in our existing project:

npm install vue-router@latest
Enter fullscreen mode

Exit fullscreen mode

3.In our project, we will have a folder called View, it may contain some files(HomeView.vue and AboutView.vue). Additional view files are welcome, as seen in the code below:

<script setup>
// In your folder called View, setup vue components that will be used as view, three files in it(HomeView.vue, AboutView.vue, and NotFoundView.vue)
</script>

<!--HomeView.vue-->
<template>
    <div>
        <h1>Home</h1>
        <p>This is the home page</p>
    </div>
</template>
<!--AboutView.vue-->
<template>
    <div>
        <h1>About</h1>
        <p>This is the about page</p>
    </div>
</template>
<!--NotFoundView.vue-->
<template>
    <div>
        <h1>Not found</h1>
        <p>This is the 404 page</p>
    </div>
</template>
Enter fullscreen mode

Exit fullscreen mode

4.In our App.vue, under your src folder, import Router Link and Router View, use them to define your navigation routes.

<script setup>
import {routerLink,routerView} from 'vue-router'
</script>

<!--create a navigation bar with links to the home, about, and not found pages-->
<template>
   <nav>
        <RouterLink to="https://dev.to/">Home</routerLink>
        <RouterLink to="https://dev.to/about">About</routerLink>
        <RouterLink to="/not-found">Not found</routerLink>
    </nav>
    <!-- this is the view where each components will be rendered -->
    <RouterView/>
</template>
Enter fullscreen mode

Exit fullscreen mode

5.In our routes folder, under our index.js file, create your router instance by importing createWebHistory and createRouter, putting your routes in an array, making sure each route is an object that contains a path, name, component, and maybe some meta details.

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

//create a route instance using VueRouter
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
    {
        path: "https://dev.to/",
        name: 'Home',
        component: HomeView,
        meta: {
            title: 'Home',
            description: 'This is the home page'
        }
    },
      {
        path: "https://dev.to/about",
        name: 'About',
        component:()=>import('./AboutView.vue'),//allows for lazy loading
        meta: { //meta is used for search engine optimization
             title: 'About',
             description: 'This is the about page'
         }
    },
    {
        path: '/:catchAll(.*)',
        name: 'not-found',
        component:()=>import('./NotFoundView.vue'),
        meta: {
            title: 'Not found',
            description: 'This is the 404 page'
        }
    }
]
})

export default router;
Enter fullscreen mode

Exit fullscreen mode

You will notice that the AboutView and NotFoundView sections of the route file use a different value for the component option, which differs from the HomeView. Why is that the case?

This is because we are lazy loading these pages. Lazy loading of routes in Vue Router is a technique used to increase the performance of a Vue.js application by splitting the application into smaller chunks that are loaded on demand. Instead of loading all routes upfront, lazy loading loads the JavaScript for a route only when that route is visited. This can significantly reduce the initial load time of the application and improve the user experience, especially for large applications with many routes.

How does lazy loading works?
Lazy loading in Vue Router uses dynamic import statements to load route components asynchronously, as seen in the code example. When a user navigates to a route, the corresponding component is fetched from the server and then rendered.

What is meta, why is it used in routes?
If you look closely at our code example above, you will notice that all our routes have a meta property, Why?

In vue router, the meta property is used to attach metadata to routes, this metadata can be used for various purposes: search engine optimization, authentication, authorization, page titles etc. It simply aids and eases navigation.

6.Finally, in the src folder, under the main.js file, you need to inject your router into your vue instance for it to work.

const app = createApp(App)
app.use(router)
app.mount('#app')
Enter fullscreen mode

Exit fullscreen mode

Now the magic of the vue router comes to life, after refreshing the application, with a click we can seamlessly navigate through the HomeView, AboutView and NotFoundView pages of our application, by simply clicking on links or entering URLs such as /, /about, and /not-found(*) in your browser, you can access the respective pages without needing to refresh the application. Thereby enhancing user experience.

Conclusion
In conclusion, keep in mind that this is just a basic setup, it will vary from project to project. Also, vue-router has many other features like nested routes, named routes, and programmatic navigation that is not shown here but you can try on your own, just for fun. For more information, read up on the vue router. You need to realize that the journey of setting up a vue-router involves creating a seamless user experience that guides users through your application effortlessly, always bear this in mind. 

Using the vue router, I was able to transform a static project into a dynamic, multi-page application. This story shows that with the right tool, proper understanding of vue, vue router, its key features, folder and file structure of your project, among other things, we can create a seamless navigation experience for a user, through our application. Isn’t that wonderful? Would you like to try it out?

Check out our other content

Check out other tags:

Most Popular Articles