Dynamic props and custom events on modal component

Hi,

I have a component confirm delete modal which I show when I want to delete something. It’s simple component which pops up when I hit delete button. I call it like this from other vue pages:

<confirm-delete-dialog
    :show="showConfirmDeleteDialog" // true/false show or hide modal
    :item="itemToDelete" // what to delete (I want to reuse it for different things)
   @delete-user="deleteUser" // here we delete user (can be something else e.g. post)
   @close="handleCloseConfirmDelete" // what to do, when modal is closed (reset some data)
></confirm-delete-dialog>

in component I have like this:

export default {
	props: {
		show: {
			type: Boolean,
			required: true,
		},
        item: {
            type: String,
            required: true
        }
	},
	emits: ['item', 'close'],
    methods: {
        deleteItem() {
            this.$emit('item');
            this.$emit('close');
        }
    }
};

This doesn’t work as in this case I want to emit “delete-user” which is the value of props item. Vue complains about:
Vue warn]: Extraneous non-emits event listeners (deleteUser were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the “emits” option.

So in my main component deleteUser was not received as modal didn’t emit it.

I am doing this way as I want to use same modal to confirm deletion of different items.

How can I dynamical pass custom event, based from where the component was called, e.g. Delete User, Delete Post, etc.

You wouldn’t. You make the component more generic. A modal like this commonly has 2 buttons, cancel/close & confirm.

Something like:

<confirm-delete-dialog
    :show="showDeleteUserDialog"
    :context="userToDelete"
   @confirm="handleDeleteUser"
   @cancel="handleCloseConfirmDelete"
></confirm-delete-dialog>

Another approach would be to pass down the function that handles the delete as a prop, but that’s more of a React pattern as Vue prefers emits.

So basically I will always have confirm & cancel and whenever confirm is emitted, I handle on main component what method to call (handleDeleteUser, handleDeletePost, etc.)?

I will try this and will let you know.

Yes, precisely. There are a number of ways to approach modals.

One approach can be to use slots. With this method you could build it in a way that you can have common slots such as header, body, footer which gives you a lot of flexibility with the template.