README
fans-event-bus 事件总线(订阅者/发布者模式)
把事件挂载到Vue原型链上,当有消息发布的时候,对应事件会触发.
类别 | 事件 |
---|---|
订阅者 | $on() 多次监听事件 |
$off() 解除监听事件 | |
$once() 单次监听事件 | |
发布者 | $emit() 发布消息 |
install 引入
npm install 安装包
npm install fans-event-bus --save
//如果使用淘宝的镜像
cnpm install fans-event-bus --save
vue entries 入口文件
import Vue from 'vue'
import eventBus from 'fans-event-bus'
//options {Object}
Vue.use(eventBus,options)
options | 类型 | 描述 | 默认值 |
---|---|---|---|
name | String | 传入{name:'myEventBus'},使用时则是:this.myEventBus.$on() | $eventBus |
usage 使用方法
$on 长期监听
/**
* @description 绑定监听事件(可多次触发)(订阅多次)
* @param {Array,String} event
* @param {Number,String} id
* @param {Function} callback
*/
this.$eventBus.$on(event,id,callback)
注意:三个参数必须要传。
参数 | 类型 | 描述 |
---|---|---|
event | Array | 遍历绑定event,每个evnet的id均相同 |
String | 以当前id绑定event | |
id | String | 当相同event的id存在时,则当前事件直接替换旧事件。 |
Number | 同上 | |
callback | Function | 当event对应名称被emit方法调用的时候,callback会以数组的形式传入emit的所带的参数. |
$once 单次监听
/**
* @description 绑定监听事件(只触发一次)(订阅一次)
* @param {Array,String} event
* @param {Number,String} id
* @param {Function} callback
*/
this.$eventBus.$once(event,id,callback)
注意:三个参数必须要传。
参数 | 类型 | 描述 |
---|---|---|
event | Array | 遍历绑定event,每个evnet的id均相同 |
String | 以当前id绑定event | |
id | String | 当相同event的id存在时,则当前事件直接替换旧事件。 |
Number | 同上 | |
callback | Function | 当event对应名称被emit方法调用的时候,callback会以数组的形式传入emit的所带的参数. |
$off 解除监听
/**
* @description 解绑监听事件(取消订阅)
* @param {Array,String} event
* @param {Number,String} id
*/
this.$eventBus.$off(event,id)
解除监听方法
注意: 1.如果参数为空会删除所有事件。 2.如果参数只有event,则解除event下所有事件。 3.如果参数中有event和id,则解除event下对应id的事件。
参数 | 类型 | 描述 |
---|---|---|
event | Array | 遍历解除相对应event的监听事件 |
String | 直接解除相对应event的监听事件 | |
id | Number | 解除event下对应id的事件 |
String | 同上 |
$emit 发布消息 (触发事件)
/**
* @description 触发监听事件(发布)
* @param {String} event
*/
this.$eventBus.$emit(event,...arg)
触发事件,发布消息
参数 | 类型 | 描述 |
---|---|---|
event | String | 触发对应event的事件,event下所有id的事件均会触发 |
args | Any | 不定参数,可以传多个参数,该参数会在callback中接收。callback接收形式为数组 |
$typeOf 判断类型
/**
* @param {Array} arr
* @param {Boolean} warning
* @return {Object} {result:{Boolean} 判断结果,全部为true时则返回true, g_type:{Object} 返回所有value的类型}
*/
判断数据类型,并检测空值
参数 | 类型 | 描述 |
---|---|---|
arr | Array | Array [{value,key,types}] value为需要判断的值 key为值的唯一值 types为value期望的类型(boolean、number、string、function、array、date、regExp、undefined、null、object) |
warning | Boolean | 如果为true,则控制台会输出错误的类型,false则不输出 |
notice 注意事项
必须在组件销毁之前解除监听.
beforeDestroy(){
this.$eventBus.$off(event,id)
}