이상진
이상진

Reputation: 803

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?

Upvotes: 48

Views: 93235

Answers (4)

Sunny Chuang
Sunny Chuang

Reputation: 1

I used this to get query data code:

this.$router.currentRoute._value.query

Upvotes: 0

tony19
tony19

Reputation: 138216

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

Upvotes: 130

Dan
Dan

Reputation: 690

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>

Upvotes: 41

stackoverfloweth
stackoverfloweth

Reputation: 6907

you could also use the composition api to write your own composition that offers nicer syntax and gracefully handles when param is array.

const id = useRouteParam('id')

composition

import { computed, Ref } from 'vue'
import { useRoute } from 'vue-router'

export function useRouteParam(param: string, useFirstIfArray?: true): Ref<string>
export function useRouteParam(param: string, useFirstIfArray: false): Ref<string | string[]>
export function useRouteParam(param: string, useFirstIfArray = true): Ref<string | string[]> {
  const route = useRoute()

  return computed(() => {
    let paramValue = route.params[param]

    if (useFirstIfArray && Array.isArray(paramValue) && paramValue.length) {
      [paramValue] = paramValue
    }

    return paramValue
  })
}

https://github.com/PrefectHQ/vue-compositions/tree/main/src/useRouteParam

Upvotes: 0

Related Questions