Access router instance from my service - vue.js

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({ .. })
}

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

Is your auth service a Vue component?
If so, you should be able to change routes with:
this.$router.go('/new/route');

Related

cannot use vue-router routes in axios file

I need to redirect to login page if backend throws 401-Unauthorised error. But when I try to use router.push('/login) it throws router is not defined error in axios interceptor.
Here is my axios.js file.
import Vue from 'vue'
import axios from "axios"
import router from '../router'
_axios.interceptors.response.use(
function(response) {
return response
},
function(error) {
if(error.response.status == 401){
router.push('/login')
}
return Promise.reject(error)
}
)
This is router.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'Login',
meta: {
layout: 'login',
requireAuth: false,
icon: null
},
component: () => import(/* webpackChunkName: "login" */
'../components/common/auth/login-form'),
}]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
And defining {router} in axios gives this error in terminal npm run serve:
If I try with import router from '../router' in axios file I got this error:
use default export import router from '../router' instead of named import like you have in answer, `cause you have default export only in file where you define router

Uncaught SyntaxError: The requested module '/node_modules/.vite/vue.js?v=535663ae' does not provide an export named 'default'

I'm using a js framework known as griptape(used for blockchain). I'm getting this error when trying to use the vue router.
import Vue from "vue"; //Error **does not provide an export named 'default'**
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/about",
name: "About",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue"),
},
];
const router = new VueRouter({
routes,
});
export default router;
while my vue.d.ts file looks like this
import { CompilerOptions } from '#vue/compiler-dom';
import { RenderFunction } from '#vue/runtime-dom';
export declare function compile(template: string | HTMLElement, options?: CompilerOptions): RenderFunction;
export * from "#vue/runtime-dom";
export { }
router.d.ts file look like this
I think you are using Vue 3. You should check your vue-router version. If you just run npm i vue-router now, the version should be "^3.5.3". Try to use npm i vue-router#next to install newer version.
Then export router like this:
import {createRouter, createWebHistory} from 'vue-router'
const routes = [
{
path:'/',
name:"Home",
component:()=>import('./pages/Home.vue')
}
,
{
path:'/about',
name:"About",
component:()=>import('./pages/About.vue')
}
]
const router = createRouter({
history:createWebHistory(),
routes
})
export default router
You technically didn't ask a question I will try to explain the error. Your error states what you try to do, importing a default export from the module 'vue' which doesn't exist.
// some ts file
import Vue from "vue";
// the module
export default {}
If there should be a named export called 'Vue' you should write it as follows: import { Vue } from 'vue'
references:
https://www.typescriptlang.org/docs/handbook/modules.html#default-exports

Importing Vue Router inside a JavaScript file causes 'Module Parse Failed' Error

I am trying to access the router in the interceptor of axios, but when I import the file in a .js Axios file, an error Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > <template> occurs.
Here is a sample of the router.js file:
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: "/settings",
name: "settings",
component: require('#/views/Settings.vue'),
}
]
};
export default new Router(router);
And the interceptor file contains:
import router from './router';
Why do you using require('#/views/Settings.vue')?
Instead try to use import function.
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: '/settings',
name: 'settings',
component: () => import('#/views/Settings.vue'),
},
],
};
export default new Router(router);
PS: Answer your comment.
In main.js file export the instance variable:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
let vm = new Vue({
router,
render: h => h(App),
}).$mount('#app');
export default vm; // ATENTION HERE
In axios.js file import the main.js and access the $router:
import vm from './main.js';
...
// YOUR INTERCEPTOR
vm.$router.push({ name: 'settings' });
...

vue-router not pushing while inside a store

This is my store
import Vue from 'vue'
import Vuex from 'vuex'
import router from '#/main';
import mainStore from './modules/main-store';
import loginStore from './modules/login-store';
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
mainStore,
loginStore
}
});
and my login-store.js
//other imports
import router from '#/main';
const actions = {
forceLogout(){
localStorage.removeItem('token')
localStorage.removeItem('user')
delete API.defaults.headers.common['Authorization']
router.push('/login')
},
//other actions
}
And my router.js:
import store from './stores'
Vue.use(Router)
const router = new Router({
mode: 'hash',
routes: [
{
path: '/login',
name: 'login',
component: Login,
},
]
//other routes
})
//... some router.afterEach and router.beforeEach
export default router
There is a case where I need the store to force a logout and this is how I do it, I call the forceLogout action from a file named api.js
import store from './../stores';
//....
if(error_msg == 'Not_Logged'){
store.dispatch('forceLogout')
}
//....
I've tried changing an import:
import router from 'vue-router'
//...
router.push('/login')
Same thing with importing
import router from '#/main'
router.push('/login')
and I keep on getting TypeError: Cannot read property 'push' of undefined
I don't see where you're exporting your router.
router.js should include export default router so then when you import router from '#/main' it actually imports something.

Accessing vue-router from actions.ts

How do we get access to the Vue router instance from within our actions.ts file? this.$router and this.$route aren't available in the following context:
boot.ts:
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import store from './services/store'
import * as log from 'loglevel'
Vue.use(VueRouter);
log.setLevel("trace");
const router = new VueRouter({
routes,
linkActiveClass: "active"
});
new Vue({
el: '#app-root',
router: router,
store: store,
render: h => h(require('./layouts/app.vue.html'))
});
actions.ts:
import { http, httpClass } from './http';
import { DomainAppModel } from '../models/domainApps';
import Vue from 'vue';
var actions = {
LOGOUT: function ({ commit }, params) {
return new Promise((resolve, reject) => {
http.logout().then(result => {
commit('CLEAR_STATE');
// this.$router and this.$route not available
this.$router.push({
path:"login",
query: {
sessionTimedout: true,
redirect: this.$route.fullPath
}
});
});
});
}
}
export default actions
$router:
In order to access $router in the store actions you can do it like this:
move your router declaration to a separate file named router.ts
const router = new VueRouter({
routes,
linkActiveClass: "active"
});
export default router;
Import your router in actions.ts and use it instead of this.$router like this:
import router from './router';
// then use the router like this
router.push({path: 'login'})
$route.fullPath
Concerning $route.fullPath, you can pass it as a property of the payload when the action is dispatched
this.$store.dispatch('LOGOUT', {redirectPath: this.$route.fullPath})
then use it like this in the LOGOUT action
router.push({path:"login", query: {
sessionTimedout: true,
redirect: params.redirectPath
}});