亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將事件從 vue 插件發送到 vue 主應用

如何將事件從 vue 插件發送到 vue 主應用

慕森卡 2022-08-04 10:10:56
假設我有一個簡單的Vue插件:插件.jsexport 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();
查看完整描述

2 回答

?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

Vue.prototype.$myPlugin = function () {  

  return { 

    newEvent: function () { 

     this.$emit('new-event-from-plugin'); 

    }.bind(this) 

  };

然后像這樣使用它


this.$myPlugin().newEvent()


查看完整回答
反對 回復 2022-08-04
?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

在Vuejs中,當我們想要發出帶有事件的特定值并在父組件中偵聽事件時,我們使用該事件。實際上,我們在 vue 組件中玩,你想從插件中發出一個事件.js!$emit()$emit()


我建議你使用 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>


查看完整回答
反對 回復 2022-08-04
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號