I'm new to utilizing Vue
, and I am currently attempting to import
my existing router
instance into a JavaScript
class
where I manage the Authentication
.
This is the content of my router
file:
import Vue from 'vue';
import Router from 'vue-router';
import FirstRoute from '@/components/FirstRoute';
import SecondRoute from '@/components/SecondRoute';
Vue.use(Router);
export default new Router({
mode: 'history',
scrollBehavior() {
return { x: 0, y: 0 };
},
routes: [
{
path: '/',
meta: { requiredAuth: false },
name: 'FirstRoute',
component: FirstRoute,
},
{
path: '/second',
meta: { requiredAuth: false },
name: 'SecondRoute',
component: SecondRoute,
},
],
});
In the helper class
file, I am attempting to import and reuse the current router
instance to perform a push
operation on a route
within a method:
import Router from '../router'; /* Importing the router instance here */
const globalRouter = new Router(); /* Attempt 1 */
class AuthService {
constructor() {
console.log(Router); /* This console.log() displays the router instance with all routes - indicating successful import and functionality */
const routerInClass = new Router(); /* Attempt 2 */
this.doSomething();
}
}
doSomething() {
const routerInFunction = new Router(); /* Attempt 3 */
/* Results of my attempts: */
console.log(globalRouter); /* Result Attempt 1: undefined */
console.log(routerInClass); /* Result Attempt 2: undefined */
console.log(routerInFunction); /* Result Attempt 3: undefined */
console.log(Router); /* Result Attempt 4: undefined */
/* Attempting to use the imported router to push a route */
Router.push({ path: '/SecondRoute' }); /* Attempts 1-4 are not successful */
}
Background: My goal is to check if the auth token
has expired. If it has, I save the current href
using window.location.href
in the localStorage
and upon logging back in, redirect to the previous page. I am exploring the use of the Router
as the redirection seems to flicker, and I hope for smoother navigation.
Despite my efforts outlined above, none have been successful. While I can log the Router
in the constructor
, it always appears as undefined
within the function
. Any suggestions or insights?