Reputation: 655
I have some pages (in Laravel) that each includes a form with different action URI's:
<form method="post" action="/route1">
...
<button @click="emitEvent('event1')">
</form>
In Vuejs root I have only a method that calls the event globally:
const app = new Vue({
el: '#app',
methods: {
emitEvent(event, payload) {
EventBus.$emit(event, payload);
}
}
});
In my Component I have a listener for the global event:
data() {
return {
someKey: false //this value is dynamic
}
}
mounted() {
EventBus.$on('event1', (event) => {
console.log(event); //returns undefined
if(this.someKey) {
window.location = "/another-url";
//Go to this url ONLY if the is true, else go to the url from the action attibute of the form
}
});
}
So basically, if a certain condition is meet in vue, I want to load that page.
Right now, the page will load the url from html form even if the condition in vuejs is meet or not.
I tried @click.prevent="emitEvent('event1')" instead of @click but in this way, if the condition is false and the window.location doesn't run, it gets stuck.
I am thinking to access the event object and then manually preventDefault() but only if necesary, so if that's not the case, the page will load the url from the form's action, but I can't find a way to get that event object inside Vue.
I found that the event name is in EventBus._events.event1 but I can't go forward because there are only empty properties and I`m not sure haw can I access the default event so I can prevent it.
I`m sure there it must be a easier/shorter and better way then giving an id/class to each form, then access it, then get its action attribute which is the url I need and finally if access that url if the condition is not meet. This way it may work, but it's an old style maybe?
Anyway, I am stack here and I appreciate any help.
Upvotes: 0
Views: 1398
Reputation: 532
Your error is in the @click
-listener, your call:
emitEvent('event1')
calls the function with ONE param, therefore your event
-param in your function will always be 'event1' of type 'string'.
To answer your question you would have to change your @click-listener to:
@click="(e) => { emitEvent(e, 'event1') }"
Explanation:
When the @click-listener gets a function
as value it will call the function with the event
as the first (and only) param. In your case you give the @click-listener an undefined
as you dont have a return-value.
Here take a closer look at this doc.
Upvotes: 1
Reputation: 15616
I would go this way (as usual):
<form method="post" action="/route1" @submit="emitEvent('event1')">
...
<button type="submit">
</form>
This way, the submit event will obey the preventions. And then:
var that = this; // added a buffer to use in the event (hackish)
EventBus.$on('event1', (event) => {
if(that.someKey) {
window.location = "/another-url";
return false; // will prevent submission and change the url
}
return true; // will proceed submission
});
Upvotes: 1