Reputation: 126
I have a generic component(Used at multiple places), which emits a event on action. Example:
onClick(value) {
this.$emit('on-click', value); //But I want to do this only if there a listener on on-click event
// Else
this.defaultAction(); // Or if there is no listener in the parent component then do some default action.
}
I can always pass another prop for the check, but can this be done without that?
Upvotes: 1
Views: 992
Reputation: 20970
You can always use vm.$listeners
(vm
is the component instance) property to check for the presence of event handler. See the Vue.js API docs for more details. (Also, this is how it is done in JSX way of doing things both in Vue JSX and React JSX.)
But note that this is a way brittle way to think about it in Vue.js.
The problem is not if you should add extra prop to indicate presence of listener or not. The problem is the abstraction. Sometimes, you are making parent do the work and sometimes child component. In short, your workflow is fragmented and the smell of UI not being a good function of state is evident.
Either do both if/else scenarios in parent (i.e. same level of abstraction) and make it mandatory to provide listener always or do it in child component always.
Upvotes: 2
Reputation: 32
this.$listeners['on-click']
, this can be used to check if there is a adjacent listener for the event.
Upvotes: 0