Access router instance from my service

血红的双手。 提交于 2019-11-30 03:17:37

问题


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

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

Inside login function, I need to redirect user

router.go(redirect)

How can I retrieve 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 is just map routes

export default function configRouter (router) {
    router.map({ .. })
}

回答1:


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')
  }
}



回答2:


Is your auth service a Vue component?

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

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


来源:https://stackoverflow.com/questions/39373037/access-router-instance-from-my-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!