DEV Community

Cover image for Dynamic Routing in Nuxt
David Emaye
David Emaye

Posted on • Updated on

Dynamic Routing in Nuxt

Hello there πŸ‘‹

In this article, we will be talking about Dynamic Routing in Nuxt.

With Dynamic routing, we can use route changes as the conditions and render components without changing the layouts or pages completely.

Dynamic routing allows rendering your Vue components conditionally.

Vue encourages developers to use components as fundamental building blocks of web applications. This allows us to render separate components on the same page based on the conditions we like.

For example, let’s assume a requirement to display a table list of users and open a page for the user details when a particular user is selected from the table list.

With dynamic routing, you can use 2 pages components to achieve this.

route image

First, we use the route /users which is saved as users.vue to load the table list of users when the page loads. Then we use a dynamic page using a route like /users/:userId which is saved as _users.vue inside a folder of users to load the user details

user-table image

Image of the user details when a role on the table list is clicked

Getting Started

Let's quickly go over how to implement the above image.

First of all, we must learn about Dynamic Pages.

Dynamic pages can be created when you don't know the name of the page due to it coming from an API or you don't want to have to create the same page over and over again. To create a dynamic page you need to add an underscore before the .vue file name. You can name the file or directory anything you want but you must prefix it with an underscore. e.g _dynamicpage.vue.

So for our file, we would be creating a folder named users then saving it inside the folder with the name _users.vue

Then we create our Html component for _users.vue

<template>
  <div class="content">
      <div class="row-1">
        <div>
          <h6>User ID</h6>
          <p>{{users._id}}</p>
        </div>
        <div>
          <h6>Name</h6>
          <p>{{users.name}}</p>
        </div>
        <div>
          <h6>Age</h6>
          <p>{{users.age}}</p>
        </div>
      </div>
      <div class="row-2">
        <div>
          <h6>Phone Number</h6>
          <p>{{users.number}}</p>
        </div>
        <div>
          <h6>Course</h6>
          <p>{{users.course}}</p>
        </div>
        <div>
          <h6>Gender</h6>
          <p>{{users.gender}}</p>
        </div>
      </div>
      <div class="row-3">
        <div>
          <h6>Email Address</h6>
          <p>{{users.email}}</p>
        </div>
        <div>
          <h6>Origin State</h6>
          <p>{{users.state}}</p>
        </div>
        <div>
          <h6>Reg Date</h6>
          <p>{{users.date}}</p>
        </div>
      </div>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

To the main part, our script section

Since we would be getting our user's data from an api, we would be calling an api request. (I would be writing an article on how to get data from an api using different methods)

<script>
export default {
  data() {
    return {
      users: {}
    }
  },
  created () {
    this.getUsersById()
  },
  methods: {
    async getUsersById () {
      const userIdPromise = await fetch(`https://sample.api.com/users/id/${this.$route.params.users}`)
      const userIdJson = userIdPromise.json()
      userIdJson.then((res) => {
        this.users = res.data
      })
    }
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

While calling our api request, we added ${this.$route.params.user} behind the api link.

What does this do??

We used ${this.$route.params.user} to access the current route parameters within our local page.

For example, if we have a dynamic student page (student/_matricnumber.vue) and we want to access the matricnumber parameter to load the student or process information, we could access the variable like this: this.$route.params.matricnumber.

Since our dynamic page is fixed let's work on the main page /users.vue.

<template>
  <div>
    <table>
      <tr class="table-head">
        <th class="sn td-th">User ID</th>
        <th class="td-th">Name</th>
        <th class="td-th">Reg Date</th>
        <th class="td-th">Email Address</th>
        <th class="td-th">Course</th>
        <th class="td-th">Action</th>
      </tr>
      <tr 
      v-for="users in userTable" 
      :key="users._id" class="table-body" 
      @click="$router.push(`/user/${users._id}`)">
        <td class="sn td-th">{{ users._id }}</td>
        <td class="td-th">{{ users.name }}</td>
        <td class="td-th">{{ users.date }}</td>
        <td class="td-th">{{ users.email }}</td>
        <td class="td-th">{{ users.course }}</td>
      </tr>
    </table>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

what did we do??

We added an on-click function @click to the user row telling it to navigate to our dynamic page when clicked on and should also give it a url of the particular user Id i.e /user/${users._id}

So now, lets get our table data from the api

<script>
export default {
  data() {
    return {
      userTable: []
    }
  },
  created () {
    this.getUsers()
  },
  methods: {
    async getUsers() {
      const promise = await fetch('https://sample.api.com/users')
      const usersJson = promise.json()
      usersJson.then((res) => {
       this.userTable = res.data
      })
    }
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

Summary

In this article, I explained how to transfer dynamic IDs or strings generally between pages using the vue $route object. As I mentioned earlier, It is especially useful to extract data from the backend when the API requires the ID of an entity.

Please feel free to engage and comment below to ask me anything! I’m always happy to talk and help.

Thank you for Reading !!!

Useful Resources

Discussion (0)