代码拉取完成,页面将自动刷新
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会自动销毁
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。