vuejs組件交互 - 02 - 事件中心管理組件間的通信


事件中心

這個可以是一個空的全局的Vue實例,其他的組件利用這個實例emit和on自定義事件,這樣組件定義了自己的事件處理方法。

import Vue from 'Vue'

window.eventHub = new Vue();

事件監聽和注銷監聽

事件監聽應在根組件的created鈎子函數中進行,在組件銷毀前應注銷事件監聽

  //hook 
  created: function  () {
    //listen event
    window.eventHub.$on('switchComments',this.switchComments);
    window.eventHub.$on('removeIssue',this.removeIssue);
    window.eventHub.$on('saveComment',this.saveComment);
    window.eventHub.$on('removeComment',this.removeComment);

    //get init data
    var that =this;
    axios.get('issue/index')
    .then(function (resp) {
      that.issue_list=resp.data;
    });
  },
  beforeDestroy: function () {
    window.eventHub.$off('switchComments');
    window.eventHub.$off('removeIssue');
    window.eventHub.$off('saveComment');
    window.eventHub.$off('removeComment');
  }

子組件的emit事件,注意這里用的window.$emit而不是this.emit

  methods: {
    removeComment: function(index,cindex) {
      window.eventHub.$emit('removeComment', {index:index, cindex:cindex});
    },
    saveComment: function(index) {
      window.eventHub.$emit('saveComment', {index: index, comment: this.comment});
      this.comment="";
    }
  },

**Note: **這其實還不是最理想的通信方式,下一篇我們看看vuex怎么玩


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM