Dynamic routing using Vue Router

Modern web applications are highly complex, often including multiple hierarchies, routes, and paths; on its own, static routing, in which manually defined routes are non-adaptive and have a fixed value, is no longer sufficient to meet the demands of modern developers and app users.

As the name suggests, dynamic routes are far more flexible. A dynamic route lets us define multiple paths to display information according to real-time network changes. We can use dynamic routing to make URLs more memorable and user-friendly, creating pages that are similar but contain different data.

In this tutorial, we’ll explore dynamic routing in Vue using Vue Router, learning how it can improve our app’s performance. Let’s get started!

Setting up a Vue app

In order to understand dynamic routing in Vue, first, we’ll set up a new Vue application using either the Vue CLI or Yarn, respectively:

# Vue CLI
npm install -g @vue/cli
# yarn
yarn global add @vue/cli

Run the code below to verify that Vue was properly installed:

vue --version

Now, with Vue installed, we can create a new application as follows:

vue create routing-example

To create a route in Vue, we’ll need to define a path linking to the specific component that we want to display once the URL is loaded.

For our example, we’ll create an application with two pages, a homepage and a blog page. Let’s define the views for these two pages:

Note: For simplicity, the code below does not contain any styling or content for our two pages, focusing instead on the routing components:

// /views/Home.vue
<template>
  <div>
    <h1> Welcome to Home page </h1>
    <p>This is the page that opens on <strong>/</strong> route</p>
  </div>
</template>

// /views/Blogs.vue
<template>
  <div>
    <h1> Welcome to blogs page </h1>
    <p>This is the page opens on <strong>/blogs</strong> route</p>
  </div>
</template>

Adding static routes

Next, let’s add two static routes to our components. We’ll also define a component to show when the route is reached. Create a separate folder called routes; inside, create a file called index.js and add the code below:

// /router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Blogs from '../views/Blogs.vue'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    //  Added our new route file named profile.vue
    {
        path: '/blogs',
        name: 'Blogs',
        component: Blogs
    }
]

// Create Vue Router Object
const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

export default router

To run our app, we’ll add a router to our App.vue file as follows:

// App.vue
<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/blogs">Blogs</router-link>
    </div>
    <router-view/>
  </div>
</template>

<script>

export default {
  name: 'App',  
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  margin-top: 60px;
}

#nav {
  font-size: 1.25rem;
  margin: 2rem;
}
</style>

If you head over to http://localhost:8080/, you’ll see two routes that will open the homepage and the blog page.

Adding dynamic routes in Vue

Routing using static routes is fairly straightforward when your app is simple, however, realistically, your project will be more complex than just a homepage and blog page.

For example, let’s say that our blog has 100 posts, each with a unique URL. Creating a new component for each blog post and individually adding a path simply isn’t a feasible option.

Instead, we can add dynamic routing in our application. First, let’s create a new Post component, which will serve as a template for displaying each unique blog:

// /views/Post.vue
<template>
  <div>
    <h1> Welcome to Post page </h1>
    <p>This is the page that opens on <strong>/blog/{{ $route.params.id }}</strong> route</p>
  </div>
</template>

Update the router/index.js file with the new route in the routes array. Remember to include the import for the Post component.

In the code below, we use :id as a dynamic value in the route:

{
    path: '/post/:id',
    name: 'Post',
    component: Post,
}

Restart your app and head to localhost:8080/post/dynamic-routing in your browser. You should see the post page with the exact route above.

Now, when you add a new post to your blog page, the Post component creates a template for the URL, simplifying it and using :id as a dynamic value. We can programmatically pass any ID, and a single route will handle all of these requests.

Nested routes

Now that we’ve used dynamic routes to define the base structure of our blog, we can use nested routes, which combine multiple routes into a specific hierarchy, to define additional features related to the blog.

For example, suppose that we have a basic route defined for authors example.com/author. Within author, we nested the following pages for individual authors:

  • example.com/author/mohit
  • example.com/author/john

To look up all of the posts written by an individual author, we’ll nest down by one more level on the hierarchy and create a nested route that follows a structure similar to /author/mohit/posts.

First, add another element to the routes array. Inside the object that contains all the subroutes for this route, we’ll add a children field:

{
    path: '/author/:id',
    name: 'Author',
    component: Author,
    children: [
            {
                    path: 'posts',
                component: AuthorPosts,
            }
    ]
}

URL redirection

URL redirection, also known as URL forwarding, is a technique that we can use to make a single webpage available from more than one address. Essentially, when a user attempts to open a URL that has been redirected, the browser opens the URL to which the redirection was made. URL redirection is good practice for privacy protection and preventing broken links when pages are moved.

To redirect a URL, we can add the redirect attribute in the route object. For example, suppose that we want to search for a post based on the name of the article. We can use query parameters to redirect it to a similar route:

{
  // /search/postName -> /search?q=postName
  path: '/search/:postName',
  redirect: to => {
    return { path: '/search', query: { q: to.params.postName } }
  },
}

Routing using an alias

An alias is another term for accessing a particular URL. For example, if we want the site mohitkhare.com to be reachable if a user types http://www.mohitkhare.com, we can add an alias to the mohitkhare.com domain. In this case, mohitkhare.com is the parent site of the http://www.mohitkhare.com alias.

We can also add an alias to routes using the alias attribute. Continuing with our example, let’s say that we want to add an alias for the blogs route. Whenever a user goes to the posts route, they’ll see the same content that is on the blog page:

{
  path: '/blogs',
  name: 'Blogs',
  component: Blogs,
  alias: '/posts'
}

Summary

In this tutorial, we explored adding static and dynamic routes to our Vue.js application using Vue Router. We also learned how to improve and customize our routes by adding nested routes, URL redirection, and aliases.

With dynamic routing, we can send dynamic data through our routes, allowing us to simplify long, indecipherable URLs and classify webpages into nested hierarchies. Vue Router includes many other great features, like named routes and route transitions. I hope you enjoyed this tutorial!

The post Dynamic routing using Vue Router appeared first on LogRocket Blog.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Dynamic routing using Vue Router

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.