Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get params of router in vue 3?

I created a project in Vue.js 3 and TypeScript.

router.js

{
    path: "/app/:id",
    name: "Detail",
    component: Detail,
    props: true
  },

App.js

<script lang="ts">

...

onMounted(() => {
      const id = $route.params.id;
      ...
    });

But this results in an error:

"Cannot find name '$route'."

What am I doing wrong?

like image 694
이상진 Avatar asked Dec 14 '20 06:12

이상진


Video Answer


2 Answers

Vue Router 4.x provides useRoute() for that:

import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()

    onMounted(() => {
      const id = route.params.id
    })
  }
}

demo

like image 166
tony19 Avatar answered Nov 16 '22 02:11

tony19


If we are using the newest Vue 3 'script setup' SFC way, then

<script setup>
import { useRoute } from 'vue-router';

const route = useRoute();  
const id = route.params.id; // read parameter id (it is reactive) 

</script>
like image 35
Dan Avatar answered Nov 16 '22 00:11

Dan