lbris
lbris

Reputation: 1239

How to send modal result in parent component

I'm using vuejs with bootstrap-vue. I have two components. A list of objects, and my modal. I open my modal when I click on a particular button. Typically, my modal asks : "Are you sure you want to delete these records ?" for instance.

Everything works fine but I don't know how to retrieve the result of the modal in my parent component (if I clicked on 'ok', or 'cancel',...).

How should I do it ?

Since my modal is opened this way :

In my parent component (the list) :

deleteSelectedGroups () {
  const modalOptions = {
    action: 'delete',
    records: this.selectedGroups,
    recordFields: ['name', 'usersCount'],
    okTitle: 'Delete',
    okVariant: 'danger'
  }
  this.showModalConfirmation(modalOptions)
  // ...
  // if result of modal is true then ...
},

showModalConfirmation (modalOptions) {
  this.$refs.ModalConfirmation.show(modalOptions)
}

In my modal component :

show (modalOptions) {
  for (let option in modalOptions) {
    this[option] = modalOptions[option]
  }
  this.$bvModal.show('modalConfirmation')
}

Should I do it simply by returning the value with my methods ?

Or should I do the vuejs way and emit a variable to the parent ?

EDIT : How I'd like my flow to be (pseudo-code) :

deleteselectedGroups () {
  openModal()
  modalAnswer = modal.getAnswer()
  if (modalAnswer === 'OK') {
    deleteMyRecords() 
  }
}

Upvotes: 1

Views: 2774

Answers (2)

Hiws
Hiws

Reputation: 10324

So i ended up making 3 different ways of accomplishing this.

Using MsgConfirmBox's built in promise https://codesandbox.io/s/modal-send-answer-to-parent-3vbiv

This method uses the already built-in Confirm MessageBox which returns a promise that return whether the OK button was clicked or not, when resolved.

Emitting from the child to the parent: https://codesandbox.io/s/modal-send-answer-to-parent-3olms

This method $emit's a custom event to the parent, which can then be used to run a desired method. It can also pass up data to the parent, like a specific item to delete like in the codesandbox.

Implementing own promise: https://codesandbox.io/s/modal-send-answer-to-parent-py3nm

This implements a promise in our custom modal component, to gain similar behavior to the MsgConfirmBox that Bootstrap-Vue has. I personally think this method is a bit "sketchy", as you'll have to do more error handling for various scenarios to resolve/reject the promise properly.

Upvotes: 5

Jay Dadhaniya
Jay Dadhaniya

Reputation: 199

It's good to create a separate component for modal and emit an event from there as per the vuejs guide So your code will look clean and you will get your value.

Upvotes: 1

Related Questions