Im using the Vue 2 Composition API and want to access the route parameters from the Vue Router in my setup()
method.
As described in the Vue Router documentation:
Because we don't have access to
this
inside ofsetup
, we cannot directly accessthis.$router
orthis.$route
anymore. Instead we use theuseRouter
function:import { useRouter, useRoute } from 'vue-router' export default { setup() { const router = useRouter() const route = useRoute() function pushWithQuery(query) { router.push({ name: 'search', query: { ...route.query, }, }) } }, }
Unfortunately this method is not available in the Vue Router for Vue 2. What are my options here and how can I access my route parameters using the Vue 2 Composition API?
In Vue version<= 2.6 composition api you've the root
property in the setup context that refers to the root component, try out to use it instead of this
:
export default {
setup(props,context) {
const router = context.root.$router;
const route = context.root.$route;
function pushWithQuery(query) {
router.push({
name: 'search',
query: {
...route.query,
},
})
}
},
}