I
I
Ilya Myasin2017-10-18 14:11:31
Vue.js
Ilya Myasin, 2017-10-18 14:11:31

Vue: Is it possible to subscribe to events of components added via slot?

I want to make a wrapper component for modal windows. A form component is inserted into the modal window via slot. The form can generate "cancel" and "success" events, on which the window must be closed. The window itself raises the "close" event. Now it looks like this:

<a @click="showModal = true">открыть форму</a>
<Modal v-if="showModal" @close="showModal = false">
  <Form @success="showModal = false" />
</Modal>

The Modal component looks like this:
<div class="modal">
    <div class="modal__overlay"></div>
    <div class="modal__body">
        <slot />
    </div>
</div>

Is it possible to make the Modal component itself listen to the events emitted by the components added to the slot?
The first thought is to add a handler directly to the slot:
<slot @success="close()" />
But it doesn't work - there is an issue about it , Evan ruined the idea =) But it was a year ago, maybe they came up with something during this time?
The second thought is to drag the event through the DOM, but this is some kind of jamquiry programming =)
The third thought is that I don’t like this manual wrapping at all. It would be cool to call like this:
<Form modal="true" />
It is clear that this is ideologically bad, but for my task it is good. And it’s interesting how this is solved in general - apparently, a mixin is needed, but I still don’t understand what to write in it =) I
looked at the finished modals, I didn’t find anything similar, maybe someone saw it too?
UPD: By the way, there is moredynamic components , does it make sense to dig in this direction?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Gontarev, 2017-10-20
@igontarev

I will not answer exactly whether it is possible or not, but I can say for sure that this is very bad. Let's say I took your modal component and decided to add my form, and let's say it also emits a success event , and the modal closes according to your idea, but for me this will be a problem, because I don't want it to close right away, I have to change api my component

<a @click="showModal = true">открыть форму</a>
<Modal v-if="showModal" @close="showModal = false">
  <MySuperForm @success="handleSubmit" />
</Modal>

the idea itself is certainly interesting, listen to slot events, but it’s better to leave it for the modal as you wrote it for the first time, this is correct and it will be clear to everyone
PS you can generally listen to events like this
this.$parent.$on(...)
this.$children.$on(...)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question