One of the ideas for solving the communication problem of vue parent-child components


The scope between components is independent, and data often needs to be passed between components.

A is the parent component, and there are child components B and C below it.

A's data can be passed to B and C through props.
A can call the events of B and C through $broadcast to operate the data of B and C.
B and C can call A's events through $dispatch to manipulate A's data.

When B needs to operate the data of C, it will be more troublesome. It needs to $dispatch to A first, and then $broadcast to C. The more and more frequently the components involved communicate, the more difficult it is to manage and maintain.

That's what Vuex is all about. It can put data in a separate layer and provide methods for external manipulation of internal data.

=== === ===

Update:

Vue 2 is released, $dispatch and $broadcast are removed, and the communication event ping-pong will no longer occur. We need a Vue instance to act as a communication medium, which is called an event bus in the official Vue documentation.

export default new Vue();

When we need event communication between components, we only need to use $emit and $on for this event bus.

import Bus from './bus.js';

export default Vue.extend({
       
       
  template: `
  <div>{
       
       {
       
       msg}}</div>
  `,

  data: () => ({
       
       
    msg: 'Hello World!'
  }),

  created() {
       
       
    Bus.$on('setMsg', content => {
       
       
      this.msg = content;
    });
  }
});

import Bus from './bus.js';

export default Vue.extend({
       
       
  template: `
  <div @click="sendEvent">Say Hi</div>
  `,

  methods: {
       
       
    sendEvent() {
       
       
      Bus.$emit('setMsg', 'Hi Vue!');
    }
  }
});

Event bus is a practice, you can also use it in Vue 1.x.

Guess you like

Origin blog.csdn.net/qq_34986769/article/details/58585063