I'm looking to open a modal on checkbox check in vue-bootstrap.
I have a checkbox I'm not sure if it's the right approach with this but I need it to have a v-model too.
<b-form-checkbox
id="checkbox-1"
v-model="healthDocument"
name="checkbox-1"
value="accepted"
unchecked-value="not_accepted"
>
Health Documents
</b-form-checkbox>
and a modal
<div>
<b-button v-b-modal.modal-1>Launch demo modal</b-button>
<b-modal id="modal-1" title="BootstrapVue">
<p class="my-4">Hello from modal!</p>
</b-modal>
</div>
I see two approaches that I think are equally viable here:
show(id)
from checkbox handlerI think the simplest way to do this is to call the this.$bvModal.show(_id_)
function to show your modal from the checkbox's change
event:
<b-form-checkbox
id="checkbox-1"
v-model="healthDocument"
name="checkbox-1"
value="accepted"
unchecked-value="not_accepted"
@change="$bvModal.show('modal-1')"
>
Health Documents
</b-form-checkbox>
<div>
<b-modal
id="modal-1"
title="BootstrapVue"
>
<p class="my-4">Hello from modal!</p>
</b-modal>
</div>
This approach means that your modal's visibility isn't synced with the checkbox state, but that it will still open when you click the checkbox. If you want the modal to open only when the checkbox goes from unchecked to checked, then you'll need to add a conditional to the handler, so that it only fires when you're checking the checkbox:
checkHandler(checked) {
if (checked == 'accepted')
this.$bvModal.show('modal-1');
},
I initially suggested to use the modal's v-model
directive, but checkbox state is a little funky in that it doesn't necessarily store true
/ false
– it will actually store whatever value you give it as it's "checked" value. In your case, that's the string "accepted".
So instead of v-model
, I suggest using the property that underpins Bootstrap-Vue's modal's v-model
directive: visible
.
This way, the modal will be in sync with the checkbox's checked state, so that when the checkbox is checked, the modal will be open, and when it's unchecked, the modal will be closed. This makes sense if you want the checkbox to control the modal directly.
This also means that to dismiss the modal, we'll need to programmatically uncheck the checkbox (which may or may not be desirable based on your use case). Here's the full code example:
<b-form-checkbox
id="checkbox-1"
v-model="healthDocument"
name="checkbox-1"
value="accepted"
unchecked-value="not_accepted"
>
Health Documents
</b-form-checkbox>
<div>
<b-modal
id="modal-1"
title="BootstrapVue"
:visible="healthDocument == 'accepted'"
@hide="healthDocument = 'not_accepted'"
>
<p class="my-4">Hello from modal!</p>
</b-modal>
</div>