Search code examples
vue.jsvuejs2vuejs3vue-routervue-router4

Accessing Router from Inside Setup Call (Mixing Composition/Options APIs)


We're in the middle of migrating our Vue 2 application to Vue 3, and as such we have the Options API and Composition API living side by side. Most of the composition API is working fine. However...

I'm unable to do routing inside of my composition-API methods, because the Vue Router composable (that lets you access the router inside the setup() method) is unavailable until we upgrade to Vue 3 and Vue Router 4. As such, in order to get access to our globally registered router plugin, we have been defining a methods block on our components like this that handle routing:

methods: {
   changeRoute() {
     this.$router.push({ name: 'home' })
  }
}

I'd like to call this.changeRoute() as a function from within the setup block. That way I can actually write the component with the composition API and just keep the routing methods in the Vue2 style. Is this possible?

I know it's not ideal to mix the options API and composition API in a single component, but this is literally the only case I'd need to deal with.


Solution

  • Ended up posting an injection of the router itself as Tolbxela suggested, at the root level of our component:

    import { createApp } from 'vue'
    const router = createRouter()
    
    const app = createApp({
      /* other root component options */
      setup () {
        provide('router', router)
    })
    

    And then was able to access it inside of subcomponents via inject:

    export default {
      name: "MyComponent",
      setup () {
        const router = inject('router')
      }
    }