How to Use Vue Router Outside Vue Instance

July 29, 2020

Sometime we may need to access Vue router outside of the Vue instance.

For instance, let’s say that you want to show standard error message page for 401 error and that needs to be handled outside of the Vue instance like a custom rest client.

We can do that by creating named router and accessing it elsewhere

// router.js
export const router = new VueRouter({
  routes: [
    {
      path: '/standard_error',
      name: 'standard_error',
      component: StandardErrorPage, //make sure to import it before using
    }
  ]
});
// custom-rest-client.js

import router from './router'

// redirect to different route
router.push({name:'standard_error'})

// redirect to different route with params
// path object ignored params so make sure to use name if you need to pass params
router.push({name:'standard_error', params:{errorTitle:'Standard Error'}})

Reference


👋 I'm Ashik Nesin • Principal Software Engineer @Chargebee 👨‍💻• I write about web development & behinds the scenes of startup/side projects that I'm building

© 2022 Nesin Technologies LLP