Reputation: 41
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?
Upvotes: 0
Views: 6517
Reputation: 1921
If you want to use Vue Router outside Vue Components, you must import router/index.js
.
First you must change the content of router/index.js
for store the VueRouter instance.
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
Vue.use(VueRouter);
let router = null;
export default function() {
if (!router) {
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;
}
Now you can use VueRouter outside Vue Components:
<template>
<div>
<button @click="test">TEST</button>
</div>
</template>
<script>
import push from "@/service/index.js";
export default {
methods: {
test() {
push();
}
}
};
</script>
// service/index.js
import router from '@/router/index.js';
export default function() {
router().push({ name: 'About' });
}
Upvotes: 2