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?
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With