Vue2.0 between the components of the event dispatch and reception

In the development of vue, often communicate events between the two components

In vue1.0 we use $ dispatch and $ broadcast

child.vue:

this.$dispatch('eventName',this.data);

parent.vue:

event:{
    'eventName':function(data) {
        // 执行的方法
    }
}

But in vue2.0 $ dispatch and $ broadcast was abandoned, because based on the event streamed component tree is really hard to understand, and in the component structure expansion process will become more and more fragile, and only Sons adapted to communicate between the components. The easiest upgrade recommendations given by the official is to use a set of event handlers, but also clearly illustrates one example of empty vue can be done, because the Vue example implements an event interface to distribute
before the vue2.0 initialization vue , add a name to the data as objects eventhub empty vue

new Vue({
  el: '#app',
  router,
  render: h => h(App),
  data: {
    eventHub: new Vue()
  }
})

Call events within a certain trigger assembly

this.$root.eventHub.$emit('eventName', event.target);

Call event is received within another component, then the event binding except when the component destruction, use $ off method

created() {
    this.$root.eventHub.$on('eventName',(target) => {
    this.functionName(target)
  });
},
method:{
    functionName(target) {
    console.log(target);
    }
}

This article is reproduced in: ape 2048➜ https://www.mk2048.com/blog/blog.php?id=hhbh0a2jiib

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12563847.html