如何从Vue插件向Vue主应用发出事件

时间:2020-05-06 20:12:49

标签: javascript vue.js

假设我有一个简单的Vue插件:

plugin.js

export default {
  install(Vue) {
    if (this.installed) {
      return;
    }

    this.installed = true;

    Vue.prototype.$myPlugin = {
      newEvent: () => {
        this.$emit('new-event-from-plugin'); // <-- does not work :(
      }
    };
  }
}

并且我想在主Vue应用上使用它:

App.vue

<template>
  <div>My app</div>
</template>

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

  created() {
    this.$on('new-event-from-plugin', () => {
      console.log('is it working?');
    });
  },

  mounted() {
    this.$myPlugin.newEvent();
  }
}
</script>

假设我已经正确注册了插件,如何从插件发出事件并在主应用程序上收听呢?

我也尝试使用: Vue.prototype.$emit(); Vue.$root.$emit();

1 个答案:

答案 0 :(得分:0)

在Vuejs中,当我们要使用事件发出特定值并在父组件中监听该事件时,我们使用$emit()事件。实际上,我们在 vue组件中使用$emit()进行游戏,而您想从plugin.js发出事件!

我建议您使用pubsub.js。这是一个有用且令人惊叹的库,可提供您自定义的监听器。

您可以这样使用:

import PubSub from 'pubsub-js';

export default {
  install(Vue) {
    if (this.installed) {
      return;
    }

    this.installed = true;
    
    PubSub.publish('new-event-from-plugin');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template>
  <div>My app</div>
</template>

<script>
import PubSub from 'pubsub-js';

export default {
  name: 'app',

  created() {
    PubSub.subscribe('new-event-from-plugin', () => {
      console.log("it's worked!");
    });
  }
}
</script>