I’m trying to create a Dialog component and use it into another component.
When I click the button, the Dialog opens, but I don’t know how to close it.
These are the components:
Dialog:
<template>
<Dialog
header="###"
:visible="displayModal"
:breakpoints="{ '960px': '75vw', '640px': '90vw' }"
:style="{ width: '50vw' }"
:modal="true"
>
<div class="container">
// Dialog content
<template #footer>
<Button
label="Close"
class="p-button p-button-secondary"
icon="pi pi-times"
@click="closeModal"
/>
<Button
label="Guardar"
class="p-button p-button-primary"
icon="pi pi-check"
autofocus
v-model:visible="displayModal"
/>
</template>
</Dialog>
</template>
<script setup lang="ts">
import { defineEmits, ref } from "vue";
defineEmits(["update:visible"]);
const displayModal = ref(false);
const closeModal = () => {
displayModal.value = false;
};
</script>
The other component:
<template>
// Some code
<SplitButton
class="datatable-button"
icon="pi pi-pencil"
label="XXX"
:model="XXX"
@click="openModal"
/>
<ModalDialog v-model:visible="displayModal" />
</div>
</template>
<script setup lang="ts">
import ModalDialog from "@/components/modal/ModalDialog.vue";
import { ref } from "vue";
//Modal
const displayModal = ref(false);
const openModal = () => {
displayModal.value = true;
console.log("DisplayModal: ", displayModal.value);
};
</script>
I’ve tried using emits but i’m not sure how to do it.
2
Answers
I've already solved doing this: All the logic belongs to the parent, the child only emits the event.
Parent:
Child:
Replace your
closeModal
withAnd add by
ModalDialog
v-on@update:visible="closeDialog($event)"
Playground