Jenesius / vue-modal

🖖The progressive and simple modal system for Vue.js v3
https://modal.jenesius.com
MIT License
145 stars 14 forks source link

How to pass values back from modal component to parent #107

Closed dlandtaa closed 8 months ago

dlandtaa commented 8 months ago

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.

Jenesius commented 8 months ago

@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!

dlandtaa commented 8 months ago

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' }
Jenesius commented 8 months ago
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!

dlandtaa commented 8 months ago

Got it, thank you!