溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vuejs 用$emit與$on來進行兄弟組件之間的數(shù)據(jù)傳輸通信

發(fā)布時間:2020-09-30 14:00:45 來源:腳本之家 閱讀:168 作者:LiuYier 欄目:web開發(fā)

最近在學習vue組件雞組件之前通信問題,正好看到,以此來留作筆記。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Vue2-單一事件管理組件通信</title>
  <script src="vue.js"></script>
  <script type="text/javascript">

  //準備一個空的實例對象
  var Event = new Vue();

  //組件A
  var A = {
    template: `
      <div>
        <span>我是A組件的數(shù)據(jù)->{{a}}</span>
        <input type="button" value="把A數(shù)據(jù)傳給C" @click = "send">
      </div>
    `,
    methods: {
      send () {
        Event.$emit("a-msg", this.a);
      }
    },
    data () {
      return {
        a: "我是a組件中數(shù)據(jù)"
      }
    }
  };
  //組件B
  var B = {
    template: `
      <div>
        <span>我是B組件的數(shù)據(jù)->{{a}}</span>
        <input type="button" value="把B數(shù)據(jù)傳給C" @click = "send">
      </div>
    `,
    methods: {
      send () {
        Event.$emit("b-msg", this.a);
      }
    },
    data () {
      return {
        a: "我是b組件中數(shù)據(jù)"
      }
    }
  };
  //組件C
  var C = {
    template: `
      <div>
        <h4>我是C組件</h4>
        <span>接收過來A的數(shù)據(jù)為: {{a}}</span>
        <br>
        <span>接收過來B的數(shù)據(jù)為: {}</span>
      </div>
    `,
    mounted () {
      //接收A組件的數(shù)據(jù)
      Event.$on("a-msg", function (a) {
        this.a = a;
      }.bind(this));

      //接收B組件的數(shù)據(jù)
      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>

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI