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

What is the best way to make the button cover the entire width?

I have a Vuetify card with a layout where I am rendering some dynamic Vuetify components inside the card based on checkbox selection. These components can be a divider, a spacer, toolbar, or a button. However, I'm struggling to make the buttons span t ...

Creating a script in JavaScript to execute a command or query after midnight

I have a query regarding MongoDB and JavaScript (Express.js). Here is the scenario: I am working on developing a backend service for movies and TV series. I have already set up basic routes and functions. One of my requirements is to select a movie from ...

The method hasOwnProperty does not function as intended

Upon receiving a JSON object from the server ({error:true}), I attempted to verify if the key "error" exists. Surprisingly, the function hasOwnProperty returned false. Here is the snippet of code that led to this unexpected result: $http({ header ...

How to conditionally prevent event propagation to children in VueJs

This Vue component is called ColorButtonGroup, and it serves as a group of checkbox/toggle buttons. It has a maximum limit of 4 colors that can be selected. The component utilizes another component called ToggleButton, which is a simple toggle selection w ...

Utilize the Same Function for Loading Ajax Content to Handle Additional Ajax Content

I am currently trying to load all the content on my site using ajax. The code below demonstrates how I am attempting to achieve this: <script> function lage(url){ $.get(url, function(data) { $('#plus').html(data); $('[hr ...

Tips for refreshing jQuery to ensure it functions smoothly for subsequent tasks

I am facing an issue with running a second process under JQuery, as shown in the code snippet below: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type=" ...

When creating a dynamic page number using JavaScript during a print event, the height of an A4 page is not taken into

While creating my A4 invoice using HTML, CSS, and JS, everything appears correctly in the print preview. However, I am encountering an issue where the page number is not aligned properly and extra empty pages are generated automatically. Below is a snippe ...

Increase the date by one day in the minimum date field using the date picker

I've been struggling with adding one day to the minDate in my code. Despite trying multiple solutions from Stackoverflow, none of them have worked successfully. Here is the code I currently have: $('#cal_mulamhn').datepicker({ minDate ...

exchange the class using only JavaScript

I need help with a code snippet that allows for swapping classes using a loop. The objective is to click on the brown square causing it to move to the position of the blue square, while the blue square moves to the previous position of the brown square. T ...

Managing dynamic input texts in React JS without using name properties with a single onChange function

Dealing with multiple onChange events without a predefined name property has been challenging. Currently, one text input controls all inputs. I have come across examples with static inputs or single input functionality, but nothing specifically addressin ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

Transferring information among components and incorporating the ngDoCheck function

We are currently working on transferring data from one component to another using the following method. If there is no data available, we display an error message; however, if there is data present, we populate it in a select box. showGlobalError = true; ...

In React/Next.js, it seems that pressing the useState button twice is required in order for an event to trigger

When working with react/nextjs, I encountered an issue with a click event where I'm trying to use setState to modify an array. Strangely, the modification only takes effect after two clicks of the button. Here is the initial state array: const [array ...

Endless scrolling with Laravel and Vue fails to load data due to request not being sent

Welcome everyone, I am new to using vue.js. I have encountered a simple issue with infinite scroll. Even though I have configured it as shown below, when the page is reloaded, the request to fetch data from the database for page 1 is not sent. I would appr ...

Unable to disable background color for droppable element

For my project, I am working with two div boxes. My goal is to make it so that when I drag and drop box002 into another div box001, the background color of box001 should change to none. I have attempted to achieve this functionality using jQuery without s ...

Is it permissible to use multiple JWT tokens in the HTTP header?

Currently, I have implemented the jwt access and refresh token pattern for client-server communication. The method involves sending two jwt tokens in the header: the access token and the refresh token. This is done by adding the following code to the heade ...

Tips for waiting for an HTML element to load in a Selenium JavaScript testing script

I'm struggling to find a way to wait for an element to load in a javascript selenium test script. The closest thing I've come across is until.elementLocated, but it seems to throw an immediate exception. Is there a method to delay throwing the " ...

Update the content of an image in a Div without altering its filename

My application's backend updates an image file and sends the filename back to the front-end: $('#giffinal').html(ResponseGo); However, when I update the image again through the backend, the code in the div on the front-end does not change. ...

The specified dependency, * core-js/fn/symbol, could not be located

I am in the process of developing a Vue.js application with Vuex and have encountered some errors during the build. I attempted to resolve the issue by installing npm install --save core-js/fn/symbol, but unfortunately, it did not work as expected. https:/ ...

The react-native-video-controls package was used in React Native. When the onBack event was triggered, it successfully navigated back to the initial screen. However, upon returning

https://i.stack.imgur.com/GsS3d.png https://i.stack.imgur.com/HYBOU.png Attached are screenshots showing the issue I am experiencing with my video player. When I click the back button, the screen does not return to its initial state and the flatlist items ...