Utilize Vue: Bring in the router within a helper class and navigate to a specific

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?

Answer №1

When working on your helper file, there is no need to include Vue or VueRouter

import router from '../router';

class AuthService {
    constructor() {
        console.log(router);
        this.doSomething();
    }

    doSomething() {
        /* Utilize the imported router to navigate to a different route */
        router.push({ path: '/SecondRoute' });
    }
}

UPDATE : Ensure to move the doSomething function within your class structure

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing the observable's value by subscribing to it

There is a defined observable called imageOptions$ in my code: imageOptions$: Observable<BoundImagesToProject[]> = this.imagesService .getBoundImages({ projectId: this.projectId }) .pipe(map((images) => (images.data))); and it is used in the temp ...

Ways to customize the appearance of a react-chartist component

I recently created a React JS component that utilizes the amazing react ChartistGraph component. However, I've run into an issue where the default CSS of ChartistGraph seems to be conflicting with my custom styling. While there is plenty of documentat ...

Having trouble retrieving information from the server using ajax, javascript, jquery, and php

I am currently facing an issue with sending data retrieved from a jQuery call and attempting to save it to a server file using PHP. function getSVG(){ svghead = svghead + $('#test').html(); $.ajax({ type:"POST", da ...

"Proceeding to" express this redirection

Greetings, I am currently struggling to understand why res.redirect('/index') is rendering like this: <p>OK. Redirecting to <a href="/index">/</a></p> Instead of directly redirecting on the page. I searched through th ...

Tips for dynamically loading images as needed

I'm working on a simple image zoom jQuery feature using elevateZoom. You can see a Demo example here. The implementation involves the following code: <img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/> <sc ...

Adjust date by one day using the Datetimepicker tool

I have been attempting to adjust the date of my input by one day either forward or backwards, but I seem to be stuck and not making any progress. Take a look at my code: function function backDay() { var date = $('input#datetimepicker').va ...

Submit the form only when the specified conditions are met, otherwise return

Is there a way to submit a form after it has been prevented from submitting? I've searched for solutions on StackOverflow but haven't found one that works for me. Below is the code snippet in question: $(function(){ $("#loginform").submit(f ...

Can a single shield protect every part of an Angular application?

I have configured my application in a way where most components are protected, but the main page "/" is still accessible to users. I am looking for a solution that would automatically redirect unauthenticated users to "/login" without having to make every ...

Implementing JavaScript functionality based on a specific body class

Is there a way to execute this script only on a specific page with a particular body class? For example, if the page has <body class="category-type-plp"> How can I target my script to work specifically for "category-type-plp"? plpSpaceRemove: fun ...

Is there a way to automatically create distinct DOM ids every time?

As I delve into coding with JS and the DOM, I frequently encounter the need to create ids (or names) solely for the purpose of grouping DOM elements together (or associating them with each other)1. These ids (or names) are not referenced anywhere else in ...

Design Pattern of AngularJS/Bootstrap Application

Seeking guidance on structuring a small AngularJS application for a simple stock charts app. As a seasoned developer but new to AngularJS, I am looking for the best approach. App Overview The app includes a left-hand "nav" bar for adding and selecting s ...

Unable to retrieve jwt token from cookies

Currently, I am developing a website using the MERN stack and implementing JWT for authentication. My goal is to store JWT tokens in cookies. Despite invoking the res.cookie function with specified parameters (refer to the code below), I am facing difficul ...

Unity3D: Troubleshooting a Code Issue

Encountering an issue with my code and struggling to find a solution. I've tried moving my c# script up to the standard assets folder as suggested in my research but it didn't resolve the problem. Any assistance would be greatly appreciated! Than ...

Troubleshooting VueJS route naming issues

I am having an issue with named routes in my Vue app. Strangely, the same setup is working perfectly fine in another Vue project. When I click on a named router-link, the section just disappears. Upon inspecting the element in the browser, I noticed there ...

Discovering the initial element with a data attribute above zero using JQuery

I am working with a set of divs that have the class .item-wrap. At the moment, I am able to select the first div using this code snippet: $(".item-wrap:first").trigger( "click" ); Each .item-wrap element comes with a data-amount attribute. My challenge ...

Bug with IE lookahead in Regular Expressions

Currently, I am struggling to define the regular expression needed for proper validation in my ASP.NET validator. Although it works fine in Firefox, the sample string is not validating correctly in IE using the following expression: 12{2}12{0-9}1{12,13} ...

Add option button

Is there a way to dynamically add radio buttons using jQuery or JavaScript and save the data into a database? I have successfully appended input types such as text, textarea, checkbox, and select with options. Here is my code: <!DOCTYPE html> < ...

ReactJS Error: Rendering objects as a React child is not supported. If you intended to render multiple children, make sure to use an array instead

customMovieService.js: const films = [ { _id: "5b21ca3eeb7f6fbccd471815", title: "Inception", genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Sci-Fi" }, numberInStock: 8, dailyRentalRate: 2.0, publishDate: "2019-07-15T14:36:40.8 ...

The content remains constant when navigating within the same view

Vuejs3 Composition API Route File: Below is the route configuration for SingleBoard.vue, which displays content based on passed props: const routes = [ { path: "/singleboard/:dbName/:dbMethod/:securityType/:alertType", name: & ...

What is the best way to restrict navigation for a subroute in Vue.js?

One of the great things about beforeRouteLeave is its ability to prevent navigation under specific conditions. In my setup, I utilize a subroute to display a part of the page. I am looking for a way to implement a navigation guard on the subroute to prohi ...