learning-note icon indicating copy to clipboard operation
learning-note copied to clipboard

vue bus event

Open jackPanyj opened this issue 8 years ago • 0 comments

主要是为了解决组件间通信得问题。

代码:

    import Vue from 'vue'
    var bus = new Vue()

    function emitEvent(payload) {
        bus.$emit('component-communicate', payload)
    }

    function handleEmit() {
        bus.$on('component-communicate', ({key, value}) => {
            this[key] = value
        })
    }

    module.exports = {
         emitEvent,
         handleEmit
    }

install

npm install -S vue-bus-event

useage

ComponentA.vue

    import { handleEmit } from 'vue-bus-event'
    export default {
        data () {
            return {
                test: 'hehehe'
            }
        },
        created () {
            handleEmit.call(this)
        }
    }

ComponentB.vue

    import { emitEvent } from 'vue-bus-event'
    export default {
        methods: {
            sendMsg () {
                emitEvent({key: 'test', value: 'hahaha'})
            }
        }    
    }

sendMsg method will change ComponentA.vue file.

make data test from hehehe change to hahaha

jackPanyj avatar Dec 27 '16 08:12 jackPanyj