vue-final / vue-final-modal

🍕Vue Final Modal is a tiny, renderless, mobile-friendly, feature-rich modal component for Vue.js.
https://vue-final-modal.org
MIT License
864 stars 95 forks source link

How to close modal inside <VueFinalModal> #387

Closed geauser closed 7 months ago

geauser commented 10 months ago

Version

vue-final-modal: ^4.4.4 vue: 3.3.4 nuxt: ^3.6.2

OS

Mac

Question

I'd like to know how can a button directly inside <VueFinalModal> component could close the associated modal. Emitting the 'close' event inside a child component works but it does not if it's emitted like this:

<script lang="ts" setup>
import { VueFinalModal } from 'vue-final-modal';
const emits = defineEmits(['close']);
</script>

<template>
  <VueFinalModal>

   <!-- Emitting this 'close' event won't close the modal -->
    <button @click="emits('close')">Close Modal</button>

   <!-- But emitting a 'close' event in a child component will -->
    <slot />

  </VueFinalModal>
</template>
padi-dev-lucvt commented 8 months ago

same question

vladninja commented 8 months ago

Solved that by the creating a ref on close component:

<div class='some-close' @click="$emit('close')" ref="closebtn"></div>
const closebtn = ref(null)
...
closebtn.value.click()
hunterliu1003 commented 7 months ago

@geauser @padi-dev-lucvt You can use event update:modelValue

<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { VueFinalModal } from 'vue-final-modal'

defineProps<{
  title?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', modelValue: boolean): void
}>()
</script>

<template>
  <VueFinalModal
    class="flex justify-center items-center"
    content-class="flex flex-col p-4 bg-white dark:bg-black rounded border border-gray-100 dark:border-gray-800"
    @update:model-value="val => emit('update:modelValue', val)"
  >
    <div class="flex items-center h-10">
      <h1 v-if="title" class="text-2xl">
        {{ title }}
      </h1>
      <button class="ml-auto" @click="emit('update:modelValue', false)">
        <Icon icon="clarity:window-close-line" class="w-10 h-10" />
      </button>
    </div>
    <slot />
  </VueFinalModal>
</template>

See official example on Stackblitz: https://stackblitz.com/github/vue-final/vue-final-modal/tree/master/examples/vue3?file=src%2Fcomponents%2FMyModal.vue