I am using Vue3 with vue-router 4.0.5 and I am experiencing an issue where useRoute() appears to retieve the route correctly but the query of the route is undefined, even though a query exists.
For the path /search?q=vue
is it expected that searchQuery
equals vue
but it returns undefined.
In the template, {{ $route.query.q }}
correctly returns the query value.
import { useRoute } from "vue-router"
export default {
name: "Search",
setup() {
const route = useRoute()
const searchQuery = route.query.q
console.log(route)
console.log(searchQuery)
return {
searchQuery
}
}
}
<template>
<div>{{ $route.query.q }}</div>
</template>
When logging to the console, the route
object is logged correctly and contains the route's query object but searchQuery
is undefined.
I am wondering why searchQuery
is returning as undefined in this example.
The route
is updated asynchronously, and you're logging it before the update actually occurs.
When you console.log
an object, the browser automatically updates the logged value to show the latest. However, this is not true for strings, which is the reason the searchQuery
string is undefined
in the log, while the route
object is up to date.
In this case, you should use a computed
prop to get the query. And if you want to observe the changes to the query, use a watch:
import { computed, watch } from 'vue'
export default {
setup() {
const route = useRoute()
const searchQuery = computed(() => route.query.q)
watch(searchQuery, newSearchQuery => console.log(newSearchQuery))
return {
searchQuery
}
}
}