11

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?

3 Answers 3

17

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,
        },
      })
    }
  },
}
Sign up to request clarification or add additional context in comments.

2 Comments

context.root came as undefined for me. I'm using Vue 2.7.14
Try to use useRouter and useRoute to get the current router and route router.vuejs.org/guide/advanced/…
14

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

Comments

4

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

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

const route = useRoute();

1 Comment

Not sure how, but this works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.