Instance of access router from my service

I am creating an auth service ( src/services/auth.js ) with simple functions and properties.

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

Inside the login function, I need to redirect the user

 router.go(redirect) 

How to get a router instance ?


Context

In my src/main.js file I create a router.

 import VueRouter from 'vue-router' Vue.use(VueRouter) import route from './routes' const router = new VueRouter({ history: false, linkActiveClass: 'active' }) route(router) const App = Vue.extend(require('./App.vue')) 

In my src/routers.js there are only map routes

 export default function configRouter (router) { router.map({ .. }) } 
+5
source share
2 answers

You must 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') } } 
+9
source

Is your authentication service a component of Vue?

If so, you should be able to change routes:

 this.$router.go('/new/route'); 
+2
source

All Articles