2
votes

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?

1

1 Answers

3
votes

In vue 2 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,
        },
      })
    }
  },
}