Vuejs uses $emit and $on for data transmission and communication between sibling components

  • 2021-07-24 09:22:34
  • OfStack

Recently, I saw the communication problem before learning vue component chicken component, so I can keep it for note.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Vue2- Single 1 Event management component communication </title>
  <script src="vue.js"></script>
  <script type="text/javascript">

  // Prepare 1 Empty instance objects 
  var Event = new Vue();

  // Component A
  var A = {
    template: `
      <div>
        <span> I am A Component data ->{{a}}</span>
        <input type="button" value=" Put A Data transmission C" @click = "send">
      </div>
    `,
    methods: {
      send () {
        Event.$emit("a-msg", this.a);
      }
    },
    data () {
      return {
        a: " I am a Data in component "
      }
    }
  };
  // Component B
  var B = {
    template: `
      <div>
        <span> I am B Component data ->{{a}}</span>
        <input type="button" value=" Put B Data transmission C" @click = "send">
      </div>
    `,
    methods: {
      send () {
        Event.$emit("b-msg", this.a);
      }
    },
    data () {
      return {
        a: " I am b Data in component "
      }
    }
  };
  // Component C
  var C = {
    template: `
      <div>
        <h3> I am C Component </h3>
        <span> Receive it A The data of is : {{a}}</span>
        <br>
        <span> Receive it B The data of is : {{b}}</span>
      </div>
    `,
    mounted () {
      // Receive A Component data 
      Event.$on("a-msg", function (a) {
        this.a = a;
      }.bind(this));

      // Receive B Component data 
      Event.$on("b-msg", function (a) {
        this.b = a;
      }.bind(this));
    },
    data () {
      return {
        a: "",
        b: ""
      }
    }
  };
  window.onload = function () {
    new Vue({
      el: "#box",
      components: {
        "dom-a": A,
        "dom-b": B,
        "dom-c": C
      }
    });
  };


  </script>
</head>
<body>
  <div id="box">
    <dom-a></dom-a>   
    <dom-b></dom-b>   
    <dom-c></dom-c>   
  </div>

</body>
</html>

Related articles: