【问题标题】:Bootstrap Vue b-toast will not trigger a second timeBootstrap Vue b-toast 不会触发第二次
【发布时间】:2020-11-23 09:06:58
【问题描述】:

我有一系列事件消息,我想一次显示一个作为弹出消息,这些消息不会过多干扰我的网络应用程序中发生的其他事情。

我用 Bootstrap Vue b-toast 找到了一个不错的组件。

toast 显示第一个数组元素,然后,当检测到 toast“隐藏”事件时,数组“移位”以删除第一个事件消息。 然后它应该使用新的第一个数组元素重新显示 toast。

但是第二次显示 toast 的调用被忽略了。

我一直在处理一个简单的案例:

<div>
  <button v-on:click="displayEvents">Display events</button>
  <b-toast id="event-toast" static no-close-button auto-hide-delay="2000">
    {{ events[0] }}
  </b-toast>
</div>

{
  data() {
    return {
      events: []
    }
  },
  methods: {
    displayEvents() {
      this.events.push("Event 1");
      this.events.push("Event 2");
      if (this.events.length >= 1) {
        console.log('Show 1st toast - events now: ' + this.events);
        this.$bvToast.show('event-toast');
        // this.$root.$emit('bv::show::toast','event-toast')
      }
      this.$root.$on('bv::toast:hidden', bvEvent => {
        if (bvEvent.componentId == 'event-toast') {
          this.events.shift();  // Remove first element as it has now expired
          console.log('removed first element - events now: ' + this.events);
          if (this.events.length > 0) {
            console.log('Display next event');
            this.$nextTick(() => { 
              this.$bvToast.show('event-toast');
            })
            // this.$root.$emit('bv::show::toast','event-toast') 
          }
        }
      });
    }
  }
}

控制台日志表明它正在触发正确的代码来触发 toast,它使用相同的方法第二次触发它,这是第一次工作。

我也尝试过触发 toast 的“emit”方法(目前已被注释掉)。

任何想法可能是什么问题?我是在编码中出错了,还是在 Bootstrap Vue 中发现了错误?

提前致谢!

【问题讨论】:

    标签: javascript vue.js bootstrap-vue


    【解决方案1】:

    有两个问题。 displayEvents 每次运行时都会注册另一个事件侦听器。这只需要完成一次,因此将侦听器注册移动到例如created

    created() {
       this.$root.$on('bv::toast:hidden', bvEvent => {
       // ...
       });
    }
    

    我相信在第二个事件发出时存在竞争条件,其中 DOM 更改仍在从第一个事件传播(即在本例中为隐藏)。

    试试这个:

    if (this.events.length > 0) {
       console.log('Display next event:');
       this.$nextTick(() => {
          this.$bvToast.show('event-toast');
       })
    }
    

    nextTick 将回调推迟到下一个 DOM 更新周期之后。 Vue API doc 给出了这个提示:

    更改一些数据后立即使用它以等待 DOM 更新。

    【讨论】:

    • 现在它可以完美运行了 :-) 我不认为这是一个只需要创建一次的“持久”事件监听器,所以这是关键。再次感谢您的帮助!
    猜你喜欢
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多