事件总线 $emit 的别名
Aliases for event bus $emit
我想为常用的事件总线方法创建别名 $emit
、$on
等...
这样我就可以像这样引用事件总线对象:EventBus.publish(...)
我试过了:
import Vue from 'vue'
const EventBus = new Vue()
export const publish = EventBus.$emit
export const subscribe = EventBus.$on
然后:
import * as EventBus from '@/utils/eventBus.js'
但我得到 $emit is not a function
我做错了什么?
谢谢
确保绑定到对象,否则该方法将不起作用:
import Vue from 'vue'
const EventBus = new Vue()
export const publish = EventBus.$emit.bind(EventBus)
export const subscribe = EventBus.$on.bind(EventBus)
export const unsubscribe = EventBus.$off.bind(EventBus)
或更明确地说:
export function publish(name, ...args) {
EventBus.$emit(name, ...args)
}
export function subscribe(name, fn) {
EventBus.$on(name, fn)
}
export function unsubscribe(name, fn) {
EventBus.$off(name, fn)
}
你这样导入它:
import * as EventBus from './eventBus.js'
EventBus.subscribe('event', handler)
我想为常用的事件总线方法创建别名 $emit
、$on
等...
这样我就可以像这样引用事件总线对象:EventBus.publish(...)
我试过了:
import Vue from 'vue'
const EventBus = new Vue()
export const publish = EventBus.$emit
export const subscribe = EventBus.$on
然后:
import * as EventBus from '@/utils/eventBus.js'
但我得到 $emit is not a function
我做错了什么?
谢谢
确保绑定到对象,否则该方法将不起作用:
import Vue from 'vue'
const EventBus = new Vue()
export const publish = EventBus.$emit.bind(EventBus)
export const subscribe = EventBus.$on.bind(EventBus)
export const unsubscribe = EventBus.$off.bind(EventBus)
或更明确地说:
export function publish(name, ...args) {
EventBus.$emit(name, ...args)
}
export function subscribe(name, fn) {
EventBus.$on(name, fn)
}
export function unsubscribe(name, fn) {
EventBus.$off(name, fn)
}
你这样导入它:
import * as EventBus from './eventBus.js'
EventBus.subscribe('event', handler)