Get the ID from the url in VUEJS

Viewed 5266

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.

2 Answers

This can guide you if you're using vue-router

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>

This can easily done by plain javascript

const url = window.location.href;
const lastParam = url.split("/").slice(-1)[0];
console.log(lastParam);

If you are using vue-router and the page you load is defined in router.js. Then simple call this.$route.params

Related