Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the ID from the url in VUEJS

I am learning VUEJS currently and totally new to this. so i want a help. I want to have the ID from the URL such as:

URL:

abc.net/dashboard/a/123456789

I want to have the 123456789 in a text format.

like image 849
Pheonix Avatar asked Oct 18 '25 09:10

Pheonix


1 Answers

This can guide you if you're using vue-router with options api

import Vue from 'vue';
import VueRouter from 'vue-router';
import DashboardComponent from "./path/DashboardComponent";

Vue.use(VueRouter);


export default new VueRouter({
    routes: [
        
        { path: '/dashboard/a/:id', component: DashboardComponent }//where :id is the dynamic id you wish to access from the browser
    ]
})

The in your DashboardComponent

<template>
   <div> 
       {{id}} //this will show the id in plain text
   </div>
</template>

<script>
    export default {
       name: 'Dashboard',

       data(){
           return {
              id: this.$route.params.id //this is the id from the browser
           }
       },
    }
</script>

For Vue 3 with compositio API

<script setup> 
    import { defineProps, onMounted } from "vue";
    import { useRouter } from "vue-router";

    const props = defineProps( {
      id: {
        type: Number,
        required: true,
      }

    onMounted( () => {
        console.log(props.id)
    } )
    
</script>

In your router.js file,

import { createWebHistory, createRouter, } from 'vue-router'

const routes = [

    {
       name: "Dashboard", 
       path: "/dashboard/a/:id", 
       component: () => import('./components/../file.vue'), 
       props: true  
     }, 

];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

export default router;
like image 64
codervine Avatar answered Oct 21 '25 08:10

codervine