I'm new to both JS and stackoverflow, so please let me know if I need to provide more detail, or if there is a better approach.
My goal is to have a modal (preferably the msgBoxConfirm modal) close, or "Cancel" programmatically after a set time period when no input is given. I've tried wrapping it in a setTimeout and calling a time out function from within .then, but failed in both attempts.
Here is a scaffold of the code I'd like to add a time out to:
timedModalAlert: function () {
this.$bvModal.msgBoxConfirm('Session expiration in XX. Press OK to continue.')
.then(value => {
if (value == true) {
// function to refresh token
} else {
// function to log user out
}
}
)
}
My attempt:
timedModalAlert: function () {
setTimeout (() => {
this.$bvModal.msgBoxConfirm('Session expiration in XX. Press OK to continue.')
.then(value => {
if (value == true) {
// function to refresh token
} else {
// function to log user out
}
}
)
}, 1000)
Bootstrap-Vue has a method to hide modals, $bvModal.hide, which takes a modal id as it's parameter. That means if you give your modal an ID, you can then close it again later.
$bvModal.msgBoxConfirm, accepts various options as a second parameter. Including an ID, so if we give our message box an ID. We can then use this ID to close it again, after x time has passed using a setTimeout and $bvModal.hide
new Vue({
el: '#app',
methods: {
openModal() {
const modalTimeoutSeconds = 3;
const modalId = 'confirm-modal'
let modalSetTimeout = null;
this.$bvModal.msgBoxConfirm(`Session expiration in ${modalTimeoutSeconds} seconds. Press OK to continue.`, {
id: modalId
})
.then(wasOkPressed => {
if(wasOkPressed) {
/* Do something */
} else {
/* Do something else */
}
})
.catch(() => {
console.log('The modal closed unexpectedly')
})
.finally(() => {
clearTimeout(modalSetTimeout)
})
modalSetTimeout = setTimeout(() => {
this.$bvModal.hide(modalId)
}, modalTimeoutSeconds * 1000)
}
}
})
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.js"></script>
<div id="app">
<b-btn @click="openModal">
Open Modal
</b-btn>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With