Search code examples
javascriptvue.jsvuejs3vue-composition-apivue-script-setup

How to get the route parameter in the VueJs 3 composition Api


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?


Solution

  • 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 );
       }