Create a Dynamic Route With Vue Router

Share this video with your friends

Social Share Links

Send Tweet

In order to display dynamic pages we need to create dynamic routes. With Vue Router we do this by writing the route path like this /craft/:id . The : prefix indicates the dynamic part of the route.

Instructor: [0:00] We're going to create a route that has a dynamic section. We're going to have path, and it's going to be /craft, and then the craft's ID. Now, to declare a dynamic section, we prefix it with a colon, and then give the variable name that the dynamic section will be assigned to.

[0:17] We then do everything like we've done before. We'll have name, which is going to be our individual craft, and they we'll have a component, which is going to be craftView. We're going to import craftView from '@/components/CraftView.vue.'

[0:36] Let's create that craftView. I will say, craftView.vue. The first thing I want to check is I can get access to the variable name. I'll create a template for my craftView, and I'll say, "The craft ID is." To access the dynamic portion, we would use the $route, which gives us access to the global route object. Specifically, we're going to find the parameters on that, and then we want to get access to the ID.

[1:05] Let's check this out in our application. Now if I go to craft/test, the craft ID is test, because that dynamic portion, test, has been assigned to the ID parameter, and that parameter is rendered to the view.