beka
4/28/2019 - 10:05 AM

vue自行实现broadcast, dispatch

function broadcast(componentName, eventName, data) {
    this.$children.forEach(child => {
        let name = child.$options.name
        if (name === componentName) {
            // child.$emit.call(child, eventName, data)
            child.$emit(eventName, data)
        } else {
            broadcast.call(child, componentName, eventName, data)
        }
    })
}

function dispatch(componentName, eventName, data) {
    let parent = this.$parent || this.$root
    let name = parent.$options.name

    while (parent && name !== componentName) {
        parent = parent.$parent
        if (parent) {
            name = parent.$options.name
        }
    }

    if (parent) {
        parent.$emit.call(parent, eventName, data)
    }
}

export default {
    methods: {
        broadcast(componentName, eventName, data) {
            broadcast.call(this, componentName, eventName, data)
        },
        dispatch(componentName, eventName, data) {
            dispatch.call(this, componentName, eventName, data)
        }
    }
}