How to get current route via useRoute outside of router-view component

Viewed 156

How can I get the current route using useRoute for a component that's outside of the <router-view />? Is this possible?

Breadcrumbs.vue

<script setup>
import {useRoute} from 'vue-router'

const route = useRoute()
console.log(route.name) // undefined
</script>

App.vue

<template>
  <Breadcrumbs />
  <router-view />
</template>

The alternative is that I have to put <Breadcrumbs /> at the top of every single view component, and I was hoping to avoid that and instead just include it once in my App.vue

2 Answers

route.name is undefined in your example because that's the initial value when the component is rendered before the route has resolved.

For the component to reactively update based on the current route, use a watcher (e.g., watch or watchEffect):

import { watchEffect } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

watchEffect(() => {
  console.log(route.name)
})

demo

In your main file, try to mount app like this

router.isReady().then(() => {
  app.mount('#app');
});

then useRoute() should be ready in your component

Related