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.