Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Front-End Development Projects with Vue.js

You're reading from  Front-End Development Projects with Vue.js

Product type Book
Published in Nov 2020
Publisher Packt
ISBN-13 9781838984823
Pages 774 pages
Edition 1st Edition
Languages
Authors (5):
Raymond Camden Raymond Camden
Profile icon Raymond Camden
Hugo Di Francesco Hugo Di Francesco
Profile icon Hugo Di Francesco
Clifford Gurney Clifford Gurney
Profile icon Clifford Gurney
Philip Kirkbride Philip Kirkbride
Profile icon Philip Kirkbride
Maya Shavin Maya Shavin
Profile icon Maya Shavin
View More author details

Table of Contents (16) Chapters

Preface
1. Starting Your First Vue Project 2. Working with Data 3. Vue CLI 4. Nesting Components (Modularity) 5. Global Component Composition 6. Routing 7. Animations and Transitions 8. The State of Vue.js State Management 9. Working with Vuex – State, Getters, Actions, and Mutations 10. Working with Vuex – Fetching Remote Data 11. Working with Vuex – Organizing Larger Stores 12. Unit Testing 13. End-to-End Testing 14. Deploying Your Code to the Web Appendix

6. Routing

Overview

In this chapter, we will understand how routing and Vue Router work. We will also set up, implement, and manage the routing system in our app with Vue Router. Then we will look at dynamic routing for passing parameter values and nested routes for better reusability in complex applications. In addition, we will look at JavaScript Hooks, which can be used for features such as authentication and error handling. By the end of this chapter, you will be ready to handle static and dynamic routing in any Vue application.

Introduction

Routing is one of the most essential and primary parts of building dynamic web applications. You may be familiar with the word in its everyday context. For example, when we use Google Maps, we find the best route to get to a location. Routing in Vue and other frameworks is much the same. It is the process of getting a user to their desired location. When a user enters website.com/about into their URL bar, they are routed to the about page.

With Single-Page Applications (SPAs), routing allows navigation within the application to be done smoothly and without the need for page refreshing. In web development, routing is the matching mechanism by which we decide how to connect HTTP requests to the code that handles them. We use routing whenever there is a need for URL navigation in our application. Most modern web applications contain a lot of different URLs, even single-page ones. Thus, routing plays a significant role in creating a navigation system and helps users move...

Vue Router

Vue Router, as stated in the Vue.js documentation, is officially recommended as a router service for any Vue.js application. It provides a single entry point for communication between components with routes, hence controlling the flow of the application effectively, regardless of the user's behavior.

With a wide range of features, it eases the process of switching pages without the need to refresh the page.

Setting Up Vue Router

Vue Router is not installed by default; however, it can easily be enabled when creating an application with Vue CLI. Create an application by running the following command:

vue create <your-project-name>

Select the Manually select features option as shown in Figure 6.1:

Figure 6.1: Select the manual preset to create a new Vue.js project

After choosing the option to manually select features, you will be shown a list of features as presented in Figure 6.2. At the time of writing, by default Babel and...

The router-view Element

The router-view element is a functional component in which the app routing system loads the matched and up-to-date view content of any given URL path received from the user.

In short, router-view is a Vue component whose job is to do the following:

  • Render different child components
  • Mount and unmount itself automatically at any nesting level, depending on the route's given path

Without router-view, it is almost impossible to have dynamic content rendered correctly for users at runtime. For example, when a user navigates to the Home page, router-view knows and renders the content related to that page only.

In the next section, we will see how we can set the entry point (default route) of an application by passing it a prop.

Using Props to Define the Entry Point of an Application

Since router-view is a component, it can also receive props. The only prop it receives is name, which is the same name registered in the corresponding route's record defined in the router object at the initialization phase.

Any other additional attributes are passed directly to the child component of router-view during rendering. Here is an example with a class attribute:

<router-view class="main-app-view"/>

If router-view renders as a child component, we can create an associated template where the layout is defined. A very simple example of a template is as follows:

<template>
  <div>Hello World</div>
</template> 

The child component receives the passed attribute class, and the actual output after rendering becomes the following:

<div class="main-app-view">Hello World</div>

Of course, for our template to be useful, it should...

Setting Up Vue Router for Vue to Use

When we add Vue Router to our project, Vue CLI creates and adds a router folder to the code directory, containing a single auto-generated index.js file. This file contains the necessary configurations for our router.

We will navigate to the file and go through the basic predefined configuration for Vue Router.

First, you will notice that we need to import both Vue and VueRouter from the vue and vue-router packages, respectively. Then we call Vue.use (VueRouter) to install it as a plugin for use within our application:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

Vue.use is a global method, as discussed in Chapter 5, Global Component Composition. It triggers the internal install method of VueRouter together with the Vue constructor as soon as Vue is available as a global variable of the application. This method has a built-in mechanism to prevent installing a plugin more than once...

Passing Route Parameters

In the previous sections of this chapter, each route was a standalone view and did not need to pass or connect any data to the other routes. But the power of routing is not limited only to this. With named routes, we can also easily enable data communication between routes.

In our example app, we want our about page to be able to receive a data string called user as the user's name from the link trigger. This can be achieved by changing the to prop from a string literal to an object literal of :to="{ name: 'about' }", and then adding a new params: { user: 'Adam' } property to that object:

<router-link :to="{ name: 'about', params: { user: 'Adam' }}">
  About
</router-link>

This change informs the router to pass the desired parameters to the About page when users click on the targeted link. These additional parameters are not visible on the rendered href link, as...

Decoupling Params with Props

In the index.js file, let's adjust the configuration of the about route with an additional property called props. By setting this property's value to true, the router will automatically understand and map $route.params into the props component accordingly:

{
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */       '../views/About.vue'),
    props: true
  }

In the About.vue file, we will declare the props type as follows:

props: {
    user: String
  }

And in the <template> section, we will replace $route.params.user with user:

<template>
  <div class="about">
    <h1>About {{user}}</h1>
  </div>
</template>

The output will still...

Router Hooks

The general flow of route navigation is described in the following diagram:

Figure 6.23: Navigation resolution flow diagram

Once navigation is triggered on a certain route, Vue Router provides several primary navigation guards, or Hooks, for developers to guard or intercept that navigation process. These guards can be hooked either globally or in the component, depending on the type. Some examples are as follows:

  • Globally: beforeEach, beforeResolve, and afterEach
  • Per component: beforeEnter
  • In-component: beforeRouteUpdate, beforeRouteEnter, and beforeRouterLeave

As seen in Figure 6.23, navigation is considered completed only after all the Hooks or guards have been resolved, including any asynchronous guard. Now, let's see how to set up beforeEach Hooks.

Setting up beforeEach Hooks

beforeEach is a global Hook and is called at the very beginning of navigation, before the other global and in-component Hooks are triggered...

Setting up in-Component Hooks

Finally, we can also use in-component Hooks as component life cycle Hooks where we want to scope those Hooks to component-level for better code maintenance or enhance the workflow where the same component needs to behave differently in a certain use case.

We can have the About component now with the beforeRouteEnter() Hook defined as follows:

<script>
export default {
  data() {
    return {
      user: ''
    }
  },
  beforeRouteEnter(to, from, next) {
    if (!to.params || !to.params.user) {
      next(comp => {
        comp.user = 'Alex'
      })
    }
    else {
      next();
    }
  }
}
</script...

Dynamic Routing

If there is a lot of data that follows the same format, such as a list of users, or a list of messages, and it's required to create a page for each of them, we need to use a routing pattern. With a routing pattern, we can create a new route dynamically from the same component based on some additional information. For example, we want to render the User view component for every user but with different id values. Vue Router provides us with the ability to use dynamic segments denoted by a colon (:) to achieve dynamic routing.

Instead of using params, which doesn't persist its value on refresh or appear in the URL, we define the required params directly in the path as follows:

{
    path: '/user/:id',
    name: 'user',
    component: () => import(/* webpackChunkName: "user" */       '../views/User.vue')
  }

In the preceding code, :id means...

Nested Routes

In reality, many applications are composed of components that consist of several multiple-level nested components. For example, /user/settings/general indicates that a general view is nested in the settings view and this settings view is nested within the user view. It represents the General information section of a user's settings page.

Most of the time, we want the URL to correspond to such a structure, as demonstrated in the following screenshot:

Figure 6.37: User with two nested views – Info and Extra

Vue Router makes it easy to achieve this structure using nested route configurations and the router-view component.

Let's go back to the User.vue view in our previous example (located in ./src/views/) and add a nested router-view component in the <template> section:

<div>
  <h1>About a user: {{$route.params.id}}</h1>
  <router-link :to="{ name: 'userinfo'...

Using Layouts

There are many ways to implement layouts in a Vue.js application. One of them is using slot and creating a static wrapper layout component on top of router-view. Despite its flexibility, this approach results in a heavy performance cost, both in the unnecessary re-creation of the component and in the extra data-fetching required on every route change.

In this section, we will discuss a better approach, which is to take advantage of the power of the dynamic component. The components are as follows:

<component :is="layout"/>

In the App.vue file, we will change the default view generated by Vue CLI to only <router-view> and a wrapper around it. This wrapper is a dynamic component that will render whatever component is defined in the layout variable:

<template>
  <div id="app">
    <component :is="layout">
      <router-view/>
 &...

Summary

Throughout this chapter, we have learned about the most basic and useful functionalities offered by Vue Router for building routing for any Vue.js application in an effective and organized manner.

router-view and router-link allow app developers to easily set up the navigation paths to their related views and maintain the SPA concept. The fact that they are Vue components themselves provides us as developers with the benefits of the Vue architecture, giving us flexibility in implementing nested views or layouts.

Defining the route as an object with different properties simplifies the architecture process, including refactoring existing paths and adding a new route to the system. Using router parameters and patterns provides dynamic routing with reusable views and allows communication and data preservation between pages.

And finally, with Hooks, we saw how we can intercept the navigation flow, setting up authentication where needed, redirecting to the desired path,...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Front-End Development Projects with Vue.js
Published in: Nov 2020 Publisher: Packt ISBN-13: 9781838984823
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}