Reputation: 803
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
Reputation: 1
I used this to get query data code:
this.$router.currentRoute._value.query
Upvotes: 0
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
})
}
}
Upvotes: 130
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
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