vuejs事件中心管理组件间的通信详解

作者:CooMark 时间:2024-05-22 10:44:27 

本文为大家分享了vuejs事件中心管理组件间的通信,供大家参考,具体内容如下

事件中心

这个可以是一个空的全局的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怎么玩

标签:vuejs,组件,事件中心
0
投稿

猜你喜欢

  • 用户分类浅谈

    2009-09-27 12:14:00
  • 解决Keras使用GPU资源耗尽的问题

    2023-06-26 05:43:51
  • django定期执行任务(实例讲解)

    2022-12-13 20:43:35
  • 互联网科技大佬推荐的12本必读书籍

    2022-08-23 12:56:38
  • python框架Django实战商城项目之工程搭建过程图文详解

    2022-12-16 16:25:57
  • PHP中SESSION使用中的一点经验总结

    2023-11-19 11:48:54
  • python利用proxybroker构建爬虫免费IP代理池的实现

    2021-10-25 21:18:25
  • 浅谈tensorflow中dataset.shuffle和dataset.batch dataset.repeat注意点

    2023-12-10 09:54:31
  • python爬虫实战之最简单的网页爬虫教程

    2022-02-06 17:03:36
  • js控制多图左右滚动切换效果代码分享

    2023-08-28 00:14:32
  • 浅谈python多线程和队列管理shell程序

    2023-05-18 05:58:25
  • MySQL的存储过程写法和Cursor的使用

    2008-12-03 15:55:00
  • Golang strings包常用字符串操作函数

    2024-02-16 22:23:14
  • Golang基础教程之字符串string实例详解

    2024-02-07 22:37:10
  • js中位数不足自动补位扩展padLeft、padRight实现代码

    2024-04-19 10:46:42
  • 详解Mysql中的JSON系列操作函数

    2024-01-20 02:08:08
  • 对tf.reduce_sum tensorflow维度上的操作详解

    2023-01-07 14:10:28
  • Python读取分割压缩TXT文本文件实例

    2023-11-04 11:17:27
  • VS2013设置护眼背景颜色

    2023-06-28 12:59:02
  • Advanced SQL Injection with MySQL

    2024-01-24 18:09:24
  • asp之家 网络编程 m.aspxhome.com