1. 程式人生 > >Vuejs 用$emit與$on來進行資料傳輸通訊

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')