Navigating through Vue Router with Dynamic Imports and Guards

I am looking to dynamically bring in data from a component file into a router file, and then allow the use of next() based on the value of the imported data.

In my App.vue file, I am using

this.$router.push({name: "Dashboard"})
when the data changes from authenticated: false to true. This change is triggered by a watch.

The issue lies in the fact that the router file will always receive the original value of false, even with dynamic importing.


App.vue

watch: {
      authenticated(){
         console.log(this.authenticated)             //This outputs 'true'
         this.$router.push({name: 'Dashboard'});     //Routing is triggered
      }
   }

router file (index.js)

{
      path: '/dashboard',
      name: 'Dashboard',
      component: Dashboard,
      beforeEnter(to, from, next){
         (async ()=>{
            const mod = await import('../view/App.vue');  //Dynamic import
            let result = mod.default.data().auth;         //Accessing the 'authenticated' value from App.vue
            console.log(result);                          //The output is 'false', but it should be 'true'
            result ? next() : next({name: 'Login'});
         })()
      }
}

I have attempted various async methods, but none have proven successful in solving the issue.

Answer №1

Implement the In-Component Guard technique within your App.vue following the guidance provided here. This approach involves removing the authentication logic from the router file and utilizing the following code snippet:

beforeRouteLeave(to, from, next) {
    if (to.name === 'Dashboard' && this.authenticated) {
        next();
    }
    else {
        next({ name: 'Login' });
    }
}

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

Connecting two fields with a line on click in AngularJS

In the top section, there are 10 fields and in the bottom section, there are another 10 fields. I want to be able to connect two fields with a line when they are clicked (one from the top section and one from the bottom section). This connection should app ...

What is the process by which a web browser executes a ".jsx" file while in development?

As a beginner in the world of react, I have successfully been able to execute the dev and build tests. One question that has been boggling my mind is how browsers handle ".js" files. I know that when a project is build, the browser runs the &quo ...

An element failing to submit using AJAX requests

I have a login form with an <a> element that I want to use for making a post request. However, when I'm examining the backend Django code during debugging, it seems to interpret the request method as GET instead of POST. HTML <form id= ...

Example of fetching Pubnub history using AngularJS

I am not a paid PubNub user. I am utilizing the example code for an Angular JS basic chat application from PubNub, and I want to access the chat history. This specific example can be found on the PubNub website. git clone https://github.com/stephenlb/an ...

Deleting a document by ObjectID in MongoDB with Node and Express without using Mongoose: A step-by-step guide

As a newcomer to backend development, I am currently using Node/Express/MongoDB with an EJS template for the frontend. I am in the process of creating a simple todo list app to practice CRUD operations without relying on Mongoose but solely native MongoDB. ...

Having trouble retrieving JSON data using ajax

I am currently working with JSON data that is being generated by my PHP code. Here is an example of how the data looks: {"Inboxunreadmessage":4, "aaData":[{ "Inboxsubject":"Email SMTP Test", "Inboxfrom":"Deepak Saini <*****@*****.co.in>"} ...

The absence of AudioPlayer may be responsible for the compilation failure on Vercel

Here is the latest code snippet import { useState, useEffect, useRef } from "react"; import { FaPlay, FaPause, FaForward, FaBackward } from "react-icons/fa"; export default function Player() { const [isPlaying, setIsPlaying] = useState(false); const [ ...

Every time an npm installation is attempted, the following error occurs: "npm ERR! Cannot read property 'resolve' of undefined."

Welcome Everyone! Currently, I am facing an issue on my dual boot system where Node and NPM were functioning smoothly on Windows 7. However, now that Windows 7 is not booting up, presumably due to hardware problems, I have resorted to using Windows 10. E ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...

Expanding a class functionality by incorporating a method through .prototype

My goal is to define a class called "User" and then add a method to the class using the "prototype" keyword. I want the method "who_auto" to be accessible to all future instances of "User". When testing this code in JSFiddle, I encountered the error messa ...

Accessing method from child component in parent component in Vue.js is a common requirement that can be easily

Is there a way to access a method in the parent component from the child component? I attempted to use mixins but found that the function was returning null instead of the expected value. However, when emitting an object, it worked fine in the parent compo ...

Tips for arranging information in ng-repeat using nested objects within JSON data on AngularJS

Looking to display an array of object properties in an Angular view. Here is the object: $scope._Json = { "foo": { "ItemDimension1": { "Item": "item1", "ItemIndex": 1, "SelectedItems": [{ "C ...

Issue with React Router version 6: displaying an empty page

I am currently grappling with implementing react-router for my react applications. However, I am encountering issues with the routing part as it consistently displays a blank page. Below are snippets of the code from the involved files: index.js import R ...

Challenges with handling Ajax responses in Ruby on Rails

I'm currently facing an issue with the Ajax response in my Rails application, and I'm unsure of how to troubleshoot it. Here is the code that is functioning correctly: View <div id="<%= dom_id(comment) %>_count"> <%= Like.wh ...

Adding a class to the body depending on the tag or href that was clicked on the previous page

Currently, I am working on two pages - the "Home-Page" and the "Landing-Page". My goal is to customize the content of the "Landing-Page" based on the button clicked on the previous page (which happens to be the "Home-Page"). Initially, I tried using ancho ...

Checking the availability of a username by sending an Ajax request every time the user types it may lead to inefficiencies and slower response times. Are there

I have developed a NodeJS authentication application. In this scenario, when a user enters a username, the system will display "username taken" if it is already in use, otherwise it will show "username available". I am interested in understanding the lim ...

Navigating the way: Directing all TypeScript transpiled files to the build folder

I am currently working on a project using Angular2/Typescript, and I have the tsconfig.js file below: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "target": "es5", "sourceMap": true, ...

active option in Opencart 2.1 is set to "selected"

I've implemented the AJAX module d_quickcheckout to speed up the checkout process on opencart 2.1 (not the default one). However, I'm encountering an issue with a field in the payment address section that is always pre-selected with the region/st ...

What is the process for importing a jquery plugin like turnjs into a React component?

After searching through countless posts on stackoverflow, it seems like there is no solution to my problem yet. So... I would like to integrate the following: into my react COMPONENT. -I attempted using the script tag in the html file, but react does no ...

When I attempt to click on the Cancel button, the database row remains undeleted

After a user clicks on the "Cancel" button, I want to reset the source and remove the iframe to prevent the file from being uploaded to the server. This function is currently working as intended. However, I am facing an issue where even after clicking on ...