Access router instance from my service

前端 未结 2 1325
别那么骄傲
别那么骄傲 2021-01-04 11:52

I create a auth service (src/services/auth.js), with just functions and properties ..

export default {
    login() { ... }
    ...
}


        
相关标签:
2条回答
  • 2021-01-04 12:27

    Is your auth service a Vue component?

    If so, you should be able to change routes with:

    this.$router.go('/new/route');
    
    0 讨论(0)
  • 2021-01-04 12:45

    You should export the router instance and then import it into the auth.js service.

    Here is my workaround with some improvements:

    src/routes.js

    export default {
      '/': {
        component: {...}
      },
      '/about': {
        component: {...}
      },
      ...
    }
    

    src/router.js

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    import Routes from './routes'
    
    Vue.use(VueRouter)
    
    const router = new VueRouter({...})
    
    router.map(Routes)
    
    // export the router instance
    export default router
    

    src/main.js

    import Router from './router'
    import App from './app'
    
    Router.start(App, '#app')
    

    src/services/auth.js

    import Router from '../router'
    
    export default {
      login () {
        // redirect
        Router.go('path')
      }
    }
    
    0 讨论(0)
提交回复
热议问题