I
I
iamdwins2020-11-22 12:59:23
Vue.js
iamdwins, 2020-11-22 12:59:23

How to pass events from a component in a slot to the slot's parent component?

I am using vuejs3.
To implement a modal window (conditionally Modal.vue ) with motley content inside, I chose the approach with slots.
Everything was fine, but there is a component with a form (conditionally Form.vue ), upon submission of which it is necessary that this modal window closes.
A simplified implementation is as follows:
Modal.vue

<template>
  <div class="modal" v-if="modalShow">
    <span class="modal__close" @click="toggleModalShow">x</span>

    <div class="modal__title">
      <slot name='modal-title'></slot>
    </div>
    <div class="modal__content">
      <slot name='modal-content'></slot>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {ref} from 'vue'

export const modalShow = ref<boolean>(false)

export function toggleModalShow() {
  modalShow.value = !modalShow.value
}
</script>

form.vue
<template>
  <form @submit="fuSubmit">
    <button type="submit">Отправить</button>
  </form>
</template>
<script lang="ts" setup>
export const fuSubmit = (e:any) => {
  e.preventDefault();
}
</script>

app.vue
<template>
  <Modal>
    <template v-slot:modal-title>Форма</template>
    <template v-slot:modal-content>
      <Form/>
    </template>
  </Modal>
</template>
<script lang="ts" setup>
</script>

And from here the question is how to intercept this event in Modal.vue when submitting the form in Form.vue.

I tried to transmit it through emit, but it turned out to intercept the event only in App.vue, but not in Modal.vue:
<template>
  <form @submit="fuSubmit">
    <button type="submit">Отправить</button>
  </form>
</template>
<script lang="ts" setup="{ emit }">
export const fuSubmit = (e:any) => {
  emit('modal-close');
  e.preventDefault();
}
</script>

ps I met similar questions, for example here .

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2020-11-22
@iamdwins

I tried to transmit via emit, but it turned out to intercept the event only in App.vue, but not in Modal.vue

And you don't have to do that in Modal. The event is generated in the contents of the slot - you cannot know in advance which one.
Catch it in the App, and control the visibility of the window from there - showModal is not needed inside Modal, make it a parameter. For example .

A
Alexey Yarkov, 2020-11-22
@yarkov Vue.js

I have not worked with Vue3 yet, but in Vue2 EMNIP you can do something like this:
https://github.com/vuejs/vue/issues/4332#issuecomm...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question