How do I call router in service files
-
I need to print router in my service file. How do I do that?
I have below folder structure in my quasar vue
src service index.js // I need to call router here src pages components router
Here is my router file routes.js
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const routes = [ { path: '/', component: () => import('layouts/MainLayout.vue'), children: [ { path: '', component: () => import('pages/Index.vue') } ] }, { path: '/login', name: 'Login', component: () => import('pages/Login.vue'), } ] if (process.env.MODE !== 'ssr') { routes.push({ path: '*', component: () => import('pages/Error404.vue') }) } export default routes
Here is my code from router/index.js
import Vue from 'vue' import VueRouter from 'vue-router' import routes from './routes' Vue.use(VueRouter) export default function ({ }) { const Router = new VueRouter({ scrollBehavior: () => ({ x: 0, y: 0 }), routes, mode: process.env.VUE_ROUTER_MODE, base: process.env.VUE_ROUTER_BASE }) Router.beforeEach((to, from, next) => { const accessToken = Cookies.getItem('token') if (accessToken === null && to.name !== 'Login') { next({ path: '/login', replace: true }) return } else { next() } }) return Router }
In service/index.js, I have tried to print router and this.$router, both of them are not working. Is there anything I am missing in my code?
-
@Christal I have something like that, in a boot.js file where I did all my authentication logic. Notice how access.
import { Notify } from 'quasar' function tokenIsValid () { let token = {} if (localStorage.getItem('gcx_token')) { token = JSON.parse(atob(localStorage.getItem('gcx_token').split('.')[1])) console.log('validacao tempo token', token.exp < (Date.now() / 1000)) if (token.exp < (Date.now() / 1000)) { localStorage.removeItem('gcx_token') Notify.create({ color: 'negative', position: 'top', message: 'Token Expirado, por favor faça login novamente', icon: 'report_problem' }) return false } return true } return false } export default ({ router, store, Vue }) => { router.beforeEach((to, from, next) => { let requiresAuth = to.matched.some(record => record.meta.requiresAuth) if (requiresAuth && !tokenIsValid()) { next('/login') } next() }) }
-
Thank you @patryckx . I need to user router.app as well in this page. If I print router, this is what I get
ƒ (_ref) { _Applications_AMPPS2_www_g2g_frontend_vue_node_modules_babel_runtime_corejs2_helpers_objectDestructuringEmpty__WEBPACK_IMPORTED_MODULE_1___default()(_ref); var Router = new vue_router__…