VueJS事件中心:组件间通信的详细
在VueJS开发中,组件间的通信是一个重要的环节。本文将为大家介绍一种通过事件中心管理组件间通信的方法,具有极高的实用价值。让我们一起来看看它是如何实现的。
一、什么是事件中心?
事件中心是一个全局的Vue实例,可以作为其他组件之间通信的桥梁。通过该实例,我们可以实现组件间的自定义事件传递。
二、如何创建事件中心?
我们可以创建一个新的Vue实例并将其赋值给window.eventHub。这样,任何组件都可以访问到这个事件中心。
```javascript
import Vue from 'Vue';
window.eventHub = new Vue();
```
三、如何监听和注销事件?
在组件的created钩子函数中,我们可以监听事件中心的事件。在组件销毁前,我们需要注销事件监听以避免不必要的错误。
```javascript
created: function () {
// 监听事件
window.eventHub.$on('switchComments', this.switchComments);
window.eventHub.$on('removeIssue', this.removeIssue);
window.eventHub.$on('saveComment', this.saveComment);
window.eventHub.$on('removeComment', this.removeComment);
// 获取初始数据
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');
}
```
四、如何在子组件中触发事件?
这里需要注意的是,子组件触发事件需要使用window.$emit而不是this.$emit。因为组件实例内部的this并不能触发全局的事件中心。示例代码如下:
```javascript
methods: {
removeComment: function(index, cindex) {