首页 > 解决方案 > VueJS 在 mixin 中使用 EventBus

问题描述

这是我的代码:

一个随机分量:

watch: {
          'notifications' : {
            handler(newVal) {
              let questionnaireTypes = ['TwoDaysConnected', 'OneWeekConnected', 'TwoWeekInactive']
              if(newVal) {
                this.checkDisplayQuestionnaire(questionnaireTypes)
              }
            },
            immediate: false
          }
        },

mixin_common.js 中的方法:

    import EventBus from "./event-bus.js"

export default window.mixin_common = {
    methods: {
        checkDisplayQuestionnaire(questionnaireTypes) {
          let stateNotifications = this.$store.state.notifications
          EventBus.$emit('openQuestionnaireExperimentationModalWithDatas', 
          stateNotifications)
        }
    }

我想用 EventBus 打开的模态组件所在的组件:

import EventBus from "./event-bus.js"

     methods: {
        openModal() {
          this.$bvModal.show('questionnaireExperimentationModal')
        },
      },
      mounted() {
        EventBus.$on('openQuestionnaireExperimentationModalWithDatas', (notifications) => {
          this.notifications = notifications
          this.openModal()
        })

事件总线.js:

import Vue from 'vue'

const EventBus = new Vue();

export default EventBus;

实际上,模态不会打开,它唯一起作用的方法是当我EventBus.$emit('openQuestionnaireExperimentationModalWithDatas', stateNotifications)直接将它放在随机组件中,而不使用 mixin,但如果可能的话,我需要用 mixin 打开它。

有人知道怎么做吗?

标签: javascriptvue.jsmixins

解决方案


推荐阅读