Vuejs 用$emit與$on來進行數據傳輸通信

Vuejs 用$emit與$on來進行兄弟組件之間的數據傳輸通信
<!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組件的數據->{{a}}</span>
        <input type="button" value="把A數據傳給C" @click = "send">
      </div>
    `,
    methods: {
      send () {
        Event.$emit("a-msg", this.a);
      }
    },
    data () {
      return {
        a: "我是a組件中數據"
      }
    }
  };
  //組件B
  var B = {
    template: `
      <div>
        <span>我是B組件的數據->{{a}}</span>
        <input type="button" value="把B數據傳給C" @click = "send">
      </div>
    `,
    methods: {
      send () {
        Event.$emit("b-msg", this.a);
      }
    },
    data () {
      return {
        a: "我是b組件中數據"
      }
    }
  };
  //組件C
  var C = {
    template: `
      <div>
        <h3>我是C組件</h3>
        <span>接收過來A的數據為: {{a}}</span>
        <br>
        <span>接收過來B的數據為: {{b}}</span>
      </div>
    `,
    mounted () {
      //接收A組件的數據
      Event.$on("a-msg", function (a) {
        this.a = a;
      }.bind(this));
 
      //接收B組件的數據
      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>
Vuejs 用$emit與$on來進行跨頁面之間的數據傳輸通信
  • on和emit的事件必須是在一個公共的實例上,才能觸發。
新建bus.js
import Vue from 'vue'

export var bus = new Vue()
App.vue里created方法里定義事件
import { bus } from 'bus.js'
// ...
created () {
  bus.$on('tip', (text) => {
    alert(text)
  })
}
Test.vue組件內調用
import { bus } from 'bus.js'
 // ...
bus.$emit('tip', '123')
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容