I'm trying to access useRoute from within a composable function. Starting with vue 3.3.2 & vue-route 4.2.0, I set up a test using npm init vue@latest
with the router enabled. No problem accessing useRoute via the composition API within the 'script setup' tag:
App.vue
<script setup>
import { RouterLink, RouterView } from 'vue-router'
import { useRoute } from 'vue-router'
const route = useRoute()
import { computed } from 'vue'
const path = computed(() => {
console.log(`step 1`)
if (!route) {
console.log(`step 2`)
return
}
if (!route.path) {
console.log(`step 3`)
return
}
console.log(`step 4`)
return route.path
})
</script>
<template>
<p>path = {{ path }}</p>
<header>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</header>
<RouterView />
</template>
In the above code, the computed function is re-calculated each times the route changes, reaching step 1 then step 4 (success).
But when I move this code to a composable it breaks:
App.vue
<script setup>
import { RouterLink, RouterView } from 'vue-router'
import path from '@/composables/useRouteTest'
</script>
composables/useRouteTest.js
import { useRoute } from 'vue-router'
const route = useRoute()
import { computed } from 'vue'
const path = computed(() => {
console.log(`step 1`)
if (!route) {
console.log(`step 2`)
return
}
if (!route.path) {
console.log(`step 3`)
return
}
console.log(`step 4`)
return route.path
})
export default {
path
}
Within the composable, the computed function never progresses beyond step 2, and is only called once, even when I navigate to different routes.
Does useRoute not work within composables?
I've spend many hours trying the following alternatives: different Vue versions; using watch instead of computed; 'useRouter' rather than 'useRoute'; using watch with async invocation (https://router.vuejs.org/guide/advanced/composition-api.html). Always the same result.