简体   繁体   English

无法通过 setTimeout() 回调以编程方式显示 Bootstrap Vue 模式

[英]Unable to programmatically show a Bootstrap Vue modal from a setTimeout() callback

I'm building a Vue CLI app (Webpack template) that uses Bootstrap Vue to display modal windows.我正在构建一个使用 Bootstrap Vue 显示模态窗口的 Vue CLI 应用程序(Webpack 模板)。 I am trying to programmatically display the modal (see Bootstrap Vue documentation for programmatically invoking the modal) from my Vue component's mounted() hook like so:我试图从我的 Vue 组件的mounted()钩子中以编程方式显示模态(请参阅 Bootstrap Vue文档以编程方式调用模态),如下所示:

<script>
export default {
  name: 'ButtonComponent',

  mounted() {
    const showModal = sessionStorage.getItem('showModal');
    if (showModal === 'yes') this.$refs.myModal.show();
  }
}
</script>

This works just fine.这工作得很好。 However, I am unable to get this to work if I introduce a setTimeout() function like this:但是,如果我引入这样的setTimeout()函数,我将无法使其工作:

<script>
export default {
  name: 'ButtonComponent',

  mounted() {
    const showModal = sessionStorage.getItem('showModal');
    if (showModal === 'yes') setTimeout(() => this.$refs.myModal.show(), 3500);
  }
}
</script>

Why doesn't this display the modal after 3.5 seconds?为什么这在 3.5 秒后不显示模态? The timeout works and I know that because I tried console.log() -ging a message from it.超时有效,我知道这是因为我尝试了console.log()从中获取消息。 I figured it could be because the Vue JS instance isn't available inside the timer so I tried declaring a const self = this;我想这可能是因为 Vue JS 实例在计时器内不可用,所以我尝试声明一个const self = this; and calling setTimeout(() => self.$refs.myModal.show(), 3500);并调用setTimeout(() => self.$refs.myModal.show(), 3500); but that didn't help either.但这也无济于事。 What am I missing here?我在这里缺少什么?

Syntactically talking, is correct.从句法上讲,是正确的。 When you use arrow functions, this is binded to the context from where it was originally called.使用箭头函数时, this绑定到最初调用它的上下文。 In your case this inside the setTimeout means the Vue instances.在您的情况下, setTimeout 中的this表示 Vue 实例。 Try to do several console.log calls like:尝试执行几个console.log调用,例如:

setTimeout(() => {
  console.log(this); // the vue instances
  console.log(this.$refs); // the $refs
  console.log(this.$refs.myModal); // the modal $ref
}, 3500)

Just to check that your $ref exists.只是为了检查您的 $ref 是否存在。 Maybe your myModal component is not binded yet?也许您的myModal组件尚未绑定?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM