Ai
1 Star 0 Fork 0

安科吉/vue2-admin-template

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
bus.js 1.70 KB
一键复制 编辑 原始数据 按行查看 历史
安科吉 提交于 2023-03-15 16:06 +08:00 . 初始化后台项目
import Vue from 'vue'
// 存储所有的事件
const EventStore = {}
const Index = new Vue()
const destoryHandler = function () {
// this 为调用此方法的vue组件
const currentEventObj = EventStore[this._uid]
if (!currentEventObj) {
return
}
for (const type in currentEventObj) {
const key = Array.isArray(type) ? type.join(',') : type
// Index 解绑事件
Index.$off(type, currentEventObj[key])
}
// 删除记录的事件集合
delete EventStore[this._uid]
}
const BusFactory = (vm) => {
// 获取当前组件实例的destroyed生命周期
const destroyed = vm.$options.destroyed
// 获取当前组件实例的uid
const uid = vm._uid
EventStore[uid] = {}
!destroyed.includes(destoryHandler) && destroyed.push(destoryHandler)
return {
$on: (type, handler) => {
const key = Array.isArray(type) ? type.join(',') : type
EventStore[uid][key] = handler
Index.$on(type, handler)
},
$off: (type, handler) => {
if (!type) {
delete EventStore[uid]
Index.$off()
return
}
const key = Array.isArray(type) ? type.join(',') : type
// 删除对应的事件
delete EventStore[uid][key]
Index.$off(type, handler)
},
$once: (...params) => Index.$once(...params),
$emit: (...params) => Index.$emit(...params)
}
}
// 这两行是允许bus不调用依然能够触发emit和once
BusFactory.$emit = (...params) => Index.$emit(...params)
BusFactory.$once = (...params) => Index.$once(...params)
export default BusFactory
// 使用说明
// this.$bus.$emit('event',data)
// this.$bus.$on('event',()=>{}) //需要手动销毁
// or
// this.$bus(this).$on('event',()=>{}) //传this会自动销毁
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ankeji/vue2-admin-template.git
git@gitee.com:ankeji/vue2-admin-template.git
ankeji
vue2-admin-template
vue2-admin-template
master

搜索帮助