Retrieve the event object from the VueJS global event bus

I am facing a situation where I have multiple pages in Laravel, each containing a form with different action URI's:

<form method="post" action="/route1">
    ...
    <button @click="emitEvent('event1')">
</form>

Within the root of my Vuejs setup, I only have a method that triggers events globally:

const app = new Vue({
    el: '#app',
    methods: {
        emitEvent(event, payload) {
            EventBus.$emit(event, payload);
        }
    }
});

In my Component, I have set up a listener for the global event:

data() {
    return {
        someKey: false //this value can change dynamically
    }
}
mounted() {
    EventBus.$on('event1', (event) => {
        console.log(event); //displays as undefined
        if(this.someKey) {
             window.location = "/another-url"; 
             //Redirect to this URL only if the condition is true; otherwise, use the URL specified in the form's action attribute
        }
    });
}

The goal is to load a specific page based on certain conditions being met within Vue.

Currently, the page loads the URL from the HTML form regardless of whether the Vue condition is fulfilled or not.

I attempted using @click.prevent="emitEvent('event1')" instead of @click, but this caused issues when the condition was false and redirection did not occur.

I am considering accessing the event object and manually preventing default behavior, specifically if necessary to prevent unwanted redirection. However, I am struggling to find a way to access this event object within Vue.

I noticed that the event name resides in EventBus._events.event1, but further exploration has led me to empty properties without clear indication of how to access the default event and apply preventDefault().

I believe there must be a more efficient and modern approach than assigning IDs/classes to forms, fetching their action attributes, and redirecting based on conditions. While this traditional method could work, it may not be the most effective solution.

As I find myself stuck at this point, any guidance or assistance would be greatly appreciated.

Answer №1

The issue lies within the @click event listener in your code:

emitEvent('event1')

This call to the function only passes one parameter, which means that the 'event' parameter in your function will always be 'event1' of type 'string'.

To address this problem, you need to modify your @click event listener as follows:

@click="(e) => { emitEvent(e, 'event1') }"

Here's why:

When you assign a function as the value for the @click event listener, it will pass the event object as the first (and only) parameter to the function. In your case, you are passing an undefined value, since there is no return value from your function.

For further clarification, refer to this documentation.

Answer №2

I typically follow this approach:

<form method="post" action="/route1" @submit="emitEvent('event1')">
    ...
    <button type="submit">
</form>

By structuring it this way, the submit event will respect the preventions. After that, handle it like so:

var that = this; // introducing a buffer for use in the event (a bit of a hack)
EventBus.$on('event1', (event) => {
    if(that.someKey) {
         window.location = "/another-url";     
         return false; // prevents submission and changes the url
    }
    return true; // continues with submission
});

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

Is it advisable to incorporate vue-resource in Vuex actions?

I am currently working on a web application that retrieves airport data from the backend. To manage states and data sharing, I am utilizing Vuex. My dilemma is whether to load the airports in my Vuex actions or within a method of my Vue instance which will ...

After the initial iteration, the .length function ceases to function properly when

A validation method is set up to check the length of a user input field. It functions properly on the initial try, but does not update if I go back and modify the field. $("#user").blur(function () { if ($("#user").val().length < 3) { $("#userval ...

Clone the "big" div element and insert data within it

Is there a way to dynamically generate div elements while looping through a JSON array? I have various data items that I need to display in separate thumbnails within a row. I am looking for a template structure like the following: for(var i = 0; i < ...

Arrange the array so that the item is placed at the beginning while maintaining the original order

Currently facing a roadblock with this particular issue. I am attempting to create a function that accepts an index as input and rearranges the element at that index in an array to be placed at the beginning, while keeping the order of the other elements a ...

What is the process for choosing every child (regardless of level) of a parent using jQuery?

Is there a way to unbind all elements from a parent node using jQuery? How can I effectively select all children, regardless of their nesting level, from a parent node? I attempted the following: $('#google_translate_element *').unbind('c ...

The Next.js React application fails to load the updated page when clicking on a Link

I am currently working with Next.js version 14, utilizing the App router and the Link component from Next.js's next/link. In my file structure, within folder app/a, there are: page.tsx which fetches data from an API and passes it to the <Table/> ...

Having trouble running tests on the Express.js server

I'm struggling to run basic tests on my expressjs server and close it immediately. I have exported the server as a promise, but can't seem to figure out how to achieve this. Below is the code for my server file : index.js const config = require( ...

Encountering numerous errors when importing Wallet Connect / Web3 Provider

I encountered some challenges when trying to incorporate the "@walletconnect/web3-provider" JS library into my project. After installing the library along with the Web3 module using the following command: npm install --save web3 @walletconnect/web3-provide ...

developing a star rating system for a mobile website

Can star ratings be implemented in a mobile website using HTML, CSS, and JS? The HTML code for the stars is as follows: <div class="rating"> <span>☆</span><span>☆</span><span>☆</span><span>☆</sp ...

Can Angular JS apply the uppercase filter to a boolean value?

My Angular 1.4.12 binding looks like this: {{ mob.mobDataSettings[7].value | uppercase }} The first part is a boolean value from a JSON file, which can be either true or false. But when rendered in HTML, it is not showing up as uppercase (e.g. TRUE), in ...

Is there a way to customize the CSS for a single blog post and add a 5-star rating system without affecting other posts?

After launching my blog on Google's Blogger, I wanted to add a unique touch by incorporating a static 5-star rating system in my Books I Read Section. I thought about using CSS to customize each book post and display anywhere from 1 to 5 stars for vis ...

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

"Adjusting the Width of Inner Content in a Div

Here is the structure of a div: <div id="showHide"> <div>Alarm</div> <div>Alarmasdf</div> <div>Alarmasdffasdff</div> How can I obtain the width of the largest content, such as "Alarmasdffasdff"? I hav ...

What could be causing the lack of data appearing in my MongoDB database submissions?

Currently, my form successfully posts data to an mLab-hosted database, but the only information that appears is an id number and `"__v": 0'. The form consists of five input fields with corresponding names based on a defined schema. Any suggestions on ...

"Improving User Experience with React.js Serverside Rendering and Interactive Event Handling

Currently, I am in the process of learning how to utilize react.js but I am facing some challenges with using event handlers. Here's a question that has been lingering in my mind: Is it feasible to employ server-side rendering and automatically send e ...

Concealing a div based on a condition

Having difficulty concealing a div once a specific condition is met. The condition depends on the user logging into a web application. In my CSS file, I have set the multipleBox div to visibility: hidden, along with other styling attributes like border co ...

Issues with navigating routes in AngularJS

I'm currently learning Angular and having trouble with my routing setup in my application. I have a complex structure of nested modules, which makes me believe the issue lies within the injections. If anyone could provide some guidance, it would great ...

Auto-complete feature for JQuery selectors in Netbeans

For some time, I struggled with getting Netbeans to automatically complete my selectors for JQuery. Here's an example: <a id="hello" href="#">Hello</a> <script type="text/javascript"> $("|").hide(); </script> According to ...

Having trouble with JQuery Ajax when trying to send multiple data at once?

name = "John Doe"; username = "johndoe123"; password = "secure123"; $.ajax({ type: 'POST', url: "https://example.com/api", data: { name: name, username: username, password: password }, success: function(response, status, xhr ...

Is it possible to increase the width of a div by 1% within a loop using solely JavaScript?

I have been attempting to increase the width of the div by 1% using JavaScript. My goal is to create a smooth transition, but traditional animations did not work because I need to set specific conditions. window.onload = function(){ for (let i = 0 ...