猿问

如何将事件从 vue 插件发送到 vue 主应用

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


插件.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();


慕森卡
浏览 153回答 2
2回答

幕布斯6054654

Vue.prototype.$myPlugin = function () {&nbsp;&nbsp;&nbsp; return {&nbsp;&nbsp; &nbsp; newEvent: function () {&nbsp;&nbsp; &nbsp; &nbsp;this.$emit('new-event-from-plugin');&nbsp;&nbsp; &nbsp; }.bind(this)&nbsp;&nbsp; };然后像这样使用它this.$myPlugin().newEvent()

Smart猫小萌

在Vuejs中,当我们想要发出带有事件的特定值并在父组件中侦听事件时,我们使用该事件。实际上,我们在 vue 组件中玩,你想从插件中发出一个事件.js!$emit()$emit()我建议你使用 pubsub.js。这是有用和惊人的库,为您的自定义侦听器。你可以像这样使用它:import PubSub from 'pubsub-js';export default {&nbsp; install(Vue) {&nbsp; &nbsp; if (this.installed) {&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; this.installed = true;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; PubSub.publish('new-event-from-plugin');&nbsp; }}<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><template>&nbsp; <div>My app</div></template><script>import PubSub from 'pubsub-js';export default {&nbsp; name: 'app',&nbsp; created() {&nbsp; &nbsp; PubSub.subscribe('new-event-from-plugin', () => {&nbsp; &nbsp; &nbsp; console.log("it's worked!");&nbsp; &nbsp; });&nbsp; }}</script>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答