I would like to use the route and its parameters in the setup script of a component in Nuxt 3. I run into a problem when navigating by nuxt-link where the route in the setup script of the component being routed to, is the one from the component triggering the routing.
Given the following reproduction, I would expect the full path in the test component to be /test
and not /
, whether the component is routed to from the browser or from a nuxt-link. In this example however, the route is only correct when routed to from the browser or via page reload.
npx nuxi init test
cd test
npm i
/app.vue
<template>
<div>
<router-view></router-view>
</div>
</template>
/pages/index.vue
<template>
<h1>index</h1>
<nuxt-link to="/test">to test</nuxt-link>
</template>
/pages/test.vue
<template>
<h1>test</h1>
<p>Path: {{ fullPath }}</p>
</template>
<script setup lang="ts">
const fullPath = useRoute().fullPath;
console.log(fullPath);
</script>
Nuxt's built-in useRoute
requires the use of <NuxtPage>
which is a wrapper for <router-view>
and should in fact replace <router-view>
app.vue
<template>
<div>
<NuxtPage />
</div>
</template>
The rest of your code should work at this point.
For whatever reason if you do prefer the use of <router-view>
over <NuxtPage>
you can still make it work by importing vue-router's useRoute
into your component.
test.vue
import { useRoute } from 'vue-router';
const fullPath = useRoute().fullPath;
console.log(fullPath);