I have a custom input validation component that I use in a form. Something like 15 instances of this component around the app. It has a beforeDestroy
method in which I unsubscribe from global event called triggerGlobalValidation
which triggers validation before I send request to server. As expected it's triggered only once inside this certain component.
There is a container with v-if
parameter which contains one instance of the component. So when v-if="false"
I expect this certain component to unsubscribe from event and get destroyed. It goes well accept for one thing: somehow this component unsubscribes ALL other instances of it from the triggerGlobalValidation
event as well.
I've tested the behavior with v-show
and it works as expected - all other instances keep subscribed, but since the v-show
field is required for the form it's blocking validation even without being shown in the DOM. I also tested above mentioned components behavior by removing the this.$root.$off("triggerGlobalValidation")
and it also works as expected + polluting the global root.
Vue documentation on $off method is saying:
If no arguments are provided, remove all event listeners;
If only the event is provided, remove all listeners for that event;
If both event and callback are given, remove the listener for that specific callback only.
Is it possible to somehow mention in the callback, that this $off
method shouldn't unsubscribe all of its instances from the event, but just this certain one being destroyed?
Check it out in codesandbox
Specifically, we can use stop event modifier. . stop will stop the event propagation.
look, if u wanna remove/hide component from Vue app you must use data property of Vue. If you wanna destroy Vue - use method $destroy. i update my fiddle: jsfiddle.net/99yxdacy/3 when you press "toggle" - you toggle component in DOM, when you press "destroy" - you remove Vue app from DOM.
Vue Button component can be enabled/disabled by giving disabled property. To disable Vue Button component, the disabled property can be set as true .
We can access the root instance of from a child component with the $root property. The code above created a rootFoo computed property from the root Vue instance's foo component and displayed it inside the foo component. So we get foo displayed.
As answered in the issue, you need to save the handler and pass it again to $off
mounted() {
this.fn = () => {
this.toggleWarning();
}
this.$root.$on("triggerChildComponents", this.fn);
},
beforeDestroy() {
this.$root.$off("triggerChildComponents", this.fn);
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With