This is a short article to learn how to get the id parameter from Url in Vue 3.
To get the id or slug from the URL in Vue 3 first we have to create a page that will access the id/slug from the Url.
Table of Contents
So, first, we will create a page in the pages directory and name it PageDetailView.vue
.
Set the dynamic route path in router.js file
Next, we will define the dynamic route of the page in the router/index.js
file.
import { createRouter, createWebHistory } from "vue-router";
import PostDetailView from "../pages/PostDetailView.vue"
const routes = [
{
path: "/post-detail/:id",
name: 'PostDetailView'
component: PostDetailView
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
Here, we have defined the route with a path of /post-detail/:id
, where :id
is a dynamic segment that will match any string in the Url.
Get the id from the Url in Vue 3
Once we define the route in the router file, we can access the id
parameter by visiting the corresponding URL. For instance, let’s assign id123
to the id parameter, which we will access by visiting /post-detail/id123
.
Now, to access the id from the URL on our page we have to use the router
object provided by vue-router.
<template>
The Post id is: {{ postId }}
</template>
<script>
import { computed } from 'vue';
import { useRoute } from 'vue-router';
export default {
setup() {
const route = useRoute();
const postId = computed(() => route.params.id);
return {
postId,
};
},
};
</script>
Here, we have imported useRoute
from vue-router
to get access to the router object. Then we used the computed
function to dynamically extract the id
parameter from the URL.
The extracted id is then saved in the postId variable and then displayed in the template.
Alternatively, we can directly access the id parameter of an Url in the template by using $route.params.id
. For example:
<template>
The Post ID is: {{ $route.params.id }}
</template>
It is important to note that when using $route
object in the template we have to use the $
sign as the prefix to indicate it is a Vue instance property. However, in the setup function, you can access the $route
object directly without any prefix.