Home > OS >  How to get the route parameter in the VueJs 3 composition Api
How to get the route parameter in the VueJs 3 composition Api

Time:11-02

I need a route parameter in a VueJS componente. For example the 42 in example.de/page/42.

// router
// ...
    {
      path: '/pages/:id',
      name: 'pages',
      component: () => import('../views/PageView.vue'),

    },  
// ...
// PageView.vue
<script setup>
    import { onMounted } from "vue";
    import { ref } from 'vue';

    onMounted(async () => {
      console.log(  $route.params.id );
   }

Here I get the error: Uncaught (in promise) ReferenceError: $route is not defined.

But in template of the component the access with {{ $route.params.id }} is possible. But I need it in the script. What am I doing wrong?

CodePudding user response:

You need to import the useRoute and then you can access

import { useRoute } from "vue-router";

and then create route.

const route =useRoute()

CodePudding user response:

You should use the composable function useRoute :

   import { onMounted } from "vue";
    import { ref } from 'vue';
    import { useRoute } from 'vue-router'
   
   const route = useRoute()

    onMounted(async () => {
      console.log(route.params.id );
   }
  • Related