The basic principle of

Manage sibling components through the event center

  1. Separate event centers manage communication between components
let eventHub = new Vue();
Copy the code
  1. Event listening and event destruction
// The first argument is the name of the custom event and the second argument is the event function
eventHub.$on('add-todo', addTodo);
// Event destruction
eventHub.$off('add-todo')
Copy the code
  1. Triggering event
// The first argument is the name of the custom event, and the second argument is the argument carried
eventHub.$emit('add-todo', id)
Copy the code

The sample

html:

<div id='app'>
    <test-tom></test-tom>
    <test-jerry></test-jerry>
    <button @click='destroyEvent'>The destruction</button>
</div>
Copy the code

js:

// Create an event center
let hub = new Vue();

Vue.component('test-tom', {
    data: function(){
        return{
            num: 0}},template: ` < div > < div > Tom: {{num}} < / div > < button @ click = 'handle' > click < / button > < / div > `.methods: {
        handle: function() {
            // Triggers events for sibling components
            hub.$emit('jerry-event'.2)}},mounted: function() {
        // Listen on events
        hub.$on('tom-event'.(val) = > {
            this.num += val;
        })
    }
})

Vue.component('test-jerry', {
    data: function(){
        return{
            num: 0}},template: ` < div > < div > Jerry: {{num}} < / div > < button @ click = 'handle' > click < / button > < / div > `.methods: {
        handle: function() {
            // Triggers events for sibling components
            hub.$emit('tom-event'.1)}},mounted: function() {
        // Listen on events
        hub.$on('jerry-event'.(val) = > {
            this.num += val; })}})var vm = new Vue({
    el: '#app'.data: {},methods: {
        destroyEvent: function(){
            / / destroy
            hub.$off('tom-event');
            hub.$off('jerry-event'); }}})Copy the code