Access $router outside vue



  • How can I access $router in a .js file?



  • i would try to import the router where you need it:

    import router from '/router/index';  //replace with your correct path
    


  • Tried that, but the line
    router().replace({name: 'logout'}) only changes the url, without anything happening on the UI. Things work after I click F5


  • Admin

    router().push({name: 'logout'})



  • Both router().replace({name: 'logout'}) and router().replace({name: 'logout'}) only change the URL, but nothing more happens. The page isn’t changed, no errors are shown in the console. I have to click F5 and then things work (because the URL is changed to the right one)


  • Admin

    Use boot files where you have access to the instance of the Router (as param to the default export method).

    If you import and call router() you are essentially creating ANOTHER instance of the router, so nothing can actually happen to your app since your app is connected only to the initial Router.



  • Thank you @rstoenescu for the guidelines. I’m trying to use the router in a vuex action inside of a module. How would I transfer that part of the redirect logic in a boot file?



  • @reath follow what @rstoenescu suggested, then import that boot file in your vuex.
    edit. something like

    // boot/router.js
    let routerInstance = void 0
    export default async ({ router }) => {
      // something to do
      routerInstance = router
    }
    export { routerInstance }
    
    // store/somemodule/action.js
    import { routerInstance } from 'boot/router'
    export const someAction = (...) => {
      ... 
      routerInstance.push('/some-route')
    }
    

  • Admin

    If you’re using this in a Vuex store file, then it will suffice to access “this.$router”. Just make sure you don’t define your actions with ES6 arrow syntax (because “this” will mean something else as an effect).

    export const someAction(...) {
       //...
      this.$router......
    }
    


  • What are your tring to accomlish?

    In a scenario, I need to command the routing using electron menu. In this case I use electron function to fire an event and inside vue I can access a ‘bridge’ to listen for electron-initiated events. So user click on a menu and vue router change the page


Log in to reply