自定义编写Vue的全局事件总线
步骤
1.在src里面新建一个文件价,名字自定义( Bus 也可以 ,因为我就是 Bus)
2.这Bus这个文件夹里面在新建一个js文件,里面编写的 全局事件总线的代码
/**
*@import 订阅池 ( 储存 用户订阅的方法 ) 储存的规则 ( k === "string" v === "fun" )
*/
var BusDev = {};
/**
*@import 返回类型
*/
const seeType = obj => Object.prototype.toString.call(obj).slice(8, -1);
/**
*@import 订阅 (绑定) on
*/
// 订阅的钥匙 执行的回调函数
const on = function(name, callBack) {
// 判断参数是否 符合要求
if (arguments.length === 2)
// 在这里判断 是为了下面的触发所铺垫的 如果传递一个类型不为函数,再去调用会报错的
if (seeType(arguments[0]) === "String" && seeType(arguments[1]).indexOf("Function") !== -1) // 这里 indexOf 因为有很多的函数 比如: async * 函数等等呀.
BusDev[name] = callBack;
}
/**
*@import 发布 (触发) emit
*/
const emit = function(name, ...data) {
if (BusDev[name]) // 判断订阅池有没有这个方法
return BusDev[name](...data); // 需要参数展开
}
/**
*@import 取消订阅 (解绑) off
*/
const off = function() {
// 解绑有三种方式 1.参数为零 2. 参数为你规定删除那个 3. 参数为数组 删除多个
// 第一种方式
if (!arguments.length) BusDev = {};
// 第二种方式
if (arguments.length === 1 && seeType(arguments[0]) === "String") delete BusDev[arguments[0]];
// 第三种方式
if (arguments.length === 1 && seeType(arguments[0]) === "Array")
for (let i of arguments)
if (BusDev[i]) delete BusDev[i];
}
// 抛出
export default {
$on: on,
$emit: emit,
$off: off,
}
3.抛出一个对象 里面为全局事件总线的方法
4.在Vue脚手架入口文件(main.js) 引入 import bus from “./Bus”;
5.在创造Vue之前添加事件总线
new Vue({
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus = bus;
},
}).$mount('#app')
总结:以上就是自定义编写Vue事件总线的所有步骤.