首页 > 解决方案 > Bootstrap Vue - 有没有办法让消息框确认模式超时?

问题描述

我是 JS 和 stackoverflow 的新手,所以如果我需要提供更多细节,或者是否有更好的方法,请告诉我。

我的目标是关闭一个模式(最好是 msgBoxConfirm 模式),或者在没有输入的设定时间段后以编程方式“取消”。我尝试将其包装在 setTimeout 中并从 .then 中调用超时函数,但两次尝试均失败。

这是我想添加超时的代码脚手架:

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
    }
  }
  )
}

我的尝试:

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)

标签: javascriptvuejs2bootstrap-vue

解决方案


Bootstrap-Vue 有一个隐藏模态的方法$bvModal.hide,它以模态 ID 作为参数。这意味着如果你给你的模式一个ID,你可以稍后再次关闭它。

$bvModal.msgBoxConfirm, 接受各种选项作为第二个参数。包括一个ID,所以如果我们给我们的消息框一个ID. 然后我们可以使用ID它再次关闭它,在 x 时间过去后使用 asetTimeout$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/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap-vue@2.14.0/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/bootstrap-vue@2.14.0/dist/bootstrap-vue.js"></script>


<div id="app">
  <b-btn @click="openModal">
    Open Modal
  </b-btn>
</div>


推荐阅读