10

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 of setup, we cannot directly access this.$router or this.$route anymore. Instead we use the useRouter 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?

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
TheKeymaster
  • 857
  • 1
  • 11
  • 27

3 Answers3

16

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,
        },
      })
    }
  },
}
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • `context.root` came as undefined for me. I'm using Vue 2.7.14 – Pablo Jun 06 '23 at 16:57
  • Try to use `useRouter` and `useRoute` to get the current router and route https://router.vuejs.org/guide/advanced/composition-api.html#vue-router-and-the-composition-api – Boussadjra Brahim Jun 06 '23 at 19:29
11

Since version 3.6.0, useRoute (and all other composables) can be imported from vue-router/composables

camilo.forero
  • 520
  • 6
  • 10
3

The package vue2-helpers has some utils that can resolve your problem.

import { useRoute } from 'vue2-helpers/vue-router';

const route = useRoute();
Ambit Tsai
  • 31
  • 1