Jenesius/vue-modal

How to pass values back from modal component to parent

Closed this issue · 4 comments

Is your feature request related to a problem? Please describe.
I'm using Vue 3 with the composition API and I'm having trouble understanding how to return a value from the modal to the component that created it.

Describe the solution you'd like
I see that there is a way in Vue 2 to use this.$emit() to send data back to the parent component but that doesn't work in Vue 3 with the composition api. I see that the closeModal() method can maybe take an argument but I'm not sure how the parent component can get access to it.

Describe alternatives you've considered
I can hack around it by passing an emitter (using the mitt library) to the modal component as a prop and emit events back to the parent that way. Seems like there should be a cleaner way though.

Additional context
If it's not possible to return a value, I would at least like a way for the parent to know that the modal has closed.

@dlandtaa Hi!
You can read about this here.
An example implementation is here.


If this does not suit you, then give an example of your component, I will try to help!

Okay, I got it working, thank you for the help! For reference, here is how I did it using the Vue 3 composition API:

// inside the modal component
const emit = defineEmits([Modal.EVENT_PROMPT]);
...
async function save() {
    // do some work
    closeModal();
    emit(Modal.EVENT_PROMPT, { my: 'data' });
}

// inside the component that shows the modal
const res = await promptModal(ModalComponent);
// res is now { my: 'data' }
async function save() {
    // do some work
    // closeModal(); You can remove this. Prompt automatically closes the window
    emit(Modal.EVENT_PROMPT, { my: 'data' });
}

I'm glad it works great for you!

Got it, thank you!