To read more articles in this series please visit myMaking a blog, sample code please visithere.

You can run devServer through NPM start to see the tutorial code at http://localhost:8080/

$EMIT triggers events and receives events via $ON to achieve communication

Code examples: / lesson17 / SRC/components/parent, js, / lesson17 / SRC/components/child. The js

Send an event to the component by calling the component instance’s $emit(event name, parameter). In the component lifecycle Created, use \this.$on(event name, callback function), where parameters can be received, to implement communication between components.

Parent component code:

export default Vue.component('parent', {
  data() {
    return {
      num: 0,
    };
  },
  components: {
    Child
  },
  created() {
    this.$on('add'.function (n) {
      this.num = this.num + n
    })
  },
  methods: {
    addChild() {
      this.$refs.child.$emit('add'And 5)}}, the template: ` < div > < div > parent num: {{num}} < br / > < inputtype="button" value="Num1 + 5" @click="addChild" />
      <child ref="child" :parent="this"></child>
    </div>
  `
});
Copy the code

Sub-component code:

export default Vue.component('parent', {
  props: ['parent'].data() {
    return {
      num: 0,
    };
  },
  methods: {
    addParent() {
      this.parent.$emit('add'And 5)}},created() {
    this.$on('add'.function(n) {this.num = this.num + n})}, template: '<div> num: {{num}} <br/><inputtype="button" value="Parent num1 + 5" @click="addParent" />
    </div>
  `
});
Copy the code