Barrier Preventing My Access to the Page

Currently, I am working on a vue page that includes a navigation-guard. This particular page serves as an 'Update Details' section where I have implemented the use of beforeRouteLeave. The purpose of this setup is to display a warning modal if any changes are made to the details. However, I seem to have hit a roadblock in the functionality. Whenever I try to close the modal by clicking the 'Disregard Changes' button, I encounter an error message:

"Navigation aborted from "/myAccount/accountDetails" to "/contactus" via a navigation guard."

I have attempted using $emit on the click event, but I am unable to trigger my $on method in the component when the modal closes.

Component

beforeRouteLeave (to, from , next) {
    if (!this.detailsChanged) {
        next();
    } else {
        next(false);

        let data = {
            fromPage: 'PersonalDetailsPage',
            toPage: '/contactus',
            personalDetails: {
                name: this.pdName,
                comp_name: this.pdCompName,
                ddi: this.pdTelNo,
                ext: this.pdExtNo,
                mob: this.pdMobNo,
                email: this.pdEmailAdd
            }
        };
        
        VueEvent.$emit('show-details-not-saved-modal', data);
    }
}

Whole modal code

<template>
    <div class="modal fade danger-modal" id="detailsNotSavedModal" tabindex="-1" role="dialog" aria-labelledby="detailsNotSavedModal" aria-hidden="true"
            data-keyboard="false" data-backdrop="static">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content danger-modal-content">
                <div class="modal-header danger-modal-headerfooter justify-content-start">
                    Updated details not saved
                </div>
                <div class="modal-body">
                    <p>The details have changed but have not been saved.</p>
                    <p>Are you sure you want to disregard the updated details?</p>
                    <p>Clicking 'Save details' will save the updated details.</p>
                    <p>Clicking 'Disregard changes' will disregard any updated details.</p>
                </div>
                <div class="modal-footer danger-modal-headerfooter">
                    <button ref="saveButton" class="btn btn-success" type="submit" data-dismiss="modal" @click="updateDetails">Save details</button>
                    <router-link :to="navigateTo" tag="button" class="btn btn-danger" data-dismiss="modal" @click="disregardDetails">Disregard changes</router-link>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: "DetailsNotSavedModal",

    data() {
        return { 
             passedDetails: [],
             navigateTo: ''
        }
     },

    created() {
        VueEvent.$on('show-details-not-saved-modal', ( passedDetails ) => {
            this.passedDetails = passedDetails;

            console.log('passedDetails', passedDetails)

            this.navigateTo = this.passedDetails.toPage;

            $('#detailsNotSavedModal').modal('show').on('shown.bs.modal', this.focus);
        });
    },

    methods: {
        focus() {
            this.$refs.saveButton.focus();
        },

        updateDetails() {
            alert('Save clicked')
        },

        disregardDetails() {
            this.$emit('disregard_changes', { detailsChanged: false })

            // Also tried using a button and the below
            // this.$router.push(this.navigateTo);
        }
    }
}
</script>

In my attempts to resolve this issue, I have been emitting 'disregard_clicked' everywhere in my hooks but unfortunately, it never gets called.

VueEvent.$on('disregard_changes', ( data ) => {
    this.detailsChanged = data;
    console.log('0')
});

To summarize, my goal is to prevent navigation if details are changed, prompt the modal upon clicking 'Save', which would then close the modal and save the details. Clicking 'Disregard' should also close the modal and guide the user to the selected menu option.

Answer №1

VueEvent.$on('disregard_changes', ...)
is being used, but your component is emitting the event with
this.$emit('disregard_changes', ...)
, which does not send the event on the event bus in VueEvent.

Solution: Modify this.$emit to VueEvent.$emit

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

AngularJS encountered an error: The token '|' was unexpected and expected ':' instead

My HTML file contains a condition where certain fields need to be displayed automatically in landscape mode using filters. However, when I run the program, I encounter the following code: <tbody> <tr ng-repeat="ledger in vm.ledgers ...

JavaScript tool: Verify the presence of both jQuery and jQuery UI

I have been working on developing a Javascript Widget (almost complete), and when integrating it into the first site I encountered some issues. My Widget requires loading multiple libraries (jquery, jquery ui, mustache, ...); this is achieved by injecting ...

Building a promotional widget

I'm currently working on developing an ad widget that can be easily reused. I'm debating whether to use jQuery or stick with pure JavaScript for this project. What are your thoughts on the best approach for creating a versatile and efficient ad w ...

Strategies for delaying the loading of CSS when importing

import 'react-dates/lib/css/_datepicker.css' The CSS mentioned can be deferred since it is not critical. Is it possible to defer the loading of CSS when utilizing import? I found information on deferring CSS loading using <link> from Goo ...

Toggle checkbox fields based on link or checkbox selection

I need to create a functionality where specific checkbox fields (location fields) are shown or hidden based on the selection of the parent name. For example, if "United States" is selected, all US locations should appear below the United States label. I h ...

Leveraging props to set the initial value of component data in Vue 3 Composition API

Currently, I am in the process of developing a search page in Vue 3 using the composition API. One of my components is responsible for displaying a snippet of data that includes specific keywords provided by the parent component. To achieve this, I need to ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Vitek - Uncaught ReferenceError: Document Is Not Defined

Why am I encountering an error when trying to use File in my vitest code, even though I can typically use it anywhere else? How can I fix this issue? This is the content of my vite.config.ts. /// <reference types="vitest" /> import { defin ...

Updating local variable value in Node.js from an event listener

How can I modify a local variable within an event handler, listener, or function? export async function mis() { let result; // <--------- LOCAL VARIABLE I WANT TO MODIFY (currently undefined) const m = await spawn(`/cmd`); m.stdout.on('data ...

Performing a $.POST request on a Squarespace webpage

I created a custom form on my website for booking appointments, and it posts to a third-party server. When I submit the form using the <form> tag, I receive the email notification. However, I want to submit the form using $.POST so that I can customi ...

Floating division element above responsive divisions

element, I am in the process of developing a straightforward online card interface. In this interface, there will be a user profile picture displayed above some details about that user. However, to achieve this layout, the profile picture must appear hove ...

Ways to verify if the CSS background-color is set to white?

I am looking for a solution: $('*').click(function() { if($(this).css("background-color") == "#ffffff") { $(this).css("background-color") == "#000000" } });​​​​ that will execute on click of a specific cla ...

Having trouble with the updateOne() method in MongoDB - it's not updating my document nor displaying any errors. What could be the issue?

I'm currently facing an issue where I am attempting to update a user's document in the database with a value obtained from a calculator. However, despite not encountering any errors, the document does not seem to be updating and the page just con ...

When making an Ajax request, the response is received successfully, however, the success, complete, and error

I am attempting to retrieve SQL results from a database using an AJAX call and display them on another PHP page. Here is my AJAX call code: function newfunc(){ start += 10; var params = parseURLParams(document.URL); var datastring = "nextStart="+start+"&a ...

Tips for sending a tab id to a URL using jQuery

Upon examining the code snippet below, it is apparent that I am attempting to pass the value of a tab's id to a URL. In this instance, I am displaying it in HTML just for illustrative purposes; however, the hashtag id fails to be transferred to the UR ...

Updating a data value in Vue3 also updates the corresponding prop

Not sure if this is standard behavior, I'm fairly new to Vue, but it's really frustrating. Hopefully someone here can shed some light on what's going on... Here's my code snippet: props: [ 'asset', //--- asset.price = 50 ...

Is it possible to duplicate a div element and then make changes to both the original and the clone using a single button

I am dealing with an element that has three sub-elements element1, element2, and element3. When I press the button1 command, it filters element1. When I press the button2 command, it filters element2. How can I clone this element and manipulate both th ...

HTML content that is produced through JSONP retrieval

Recently, I've been experimenting with the jQuery library and have found it to be quite useful. Lately, I've been delving into AJAX requests to fetch various information like weather updates, current downloads, and more, which has been going smoo ...

ControlOrbiter - limit panning motion

Is there a way to restrict the camera's panning movement within a scene? I've experimented with adjusting the pan method in orbitControls, but I'm not completely satisfied with the outcome. I am hoping for a more convenient and proper solut ...

The dilemma of selecting objects in Three.js

Currently, I am developing a small web application that utilizes three.js. However, I have encountered an issue: I created a prototype with my three.js content and everything functions correctly (the canvas size in the prototype matches the browser window ...