先看個一般的例子:
// 我們需要將信息從子組件傳遞給父組件,(有可能不止一條信息,因此)肯定需要一個標識,這個標識放在$emit里面(js),在dom中通過@來關聯父元素。如下:<div id = "app"><transfer @connect="sayConnect" @build="sayBuild"></transfer>
</div>// js
<script>Vue.component('transfer',{template:'<button @click="send1">發送connect</button><br>'+'<button @click="send2">發送build</button>',methods:{send1(){this.$emit('connect');},send2(){this.$emit('build');}}});// 子組件注冊了2個方法,send1和send2,點擊send1發送connect,點擊send2發送build.// @connect="sayConnect", connect對應子組件中this.$emit('connect').sayConnect對應父組件的sayConnect方法,下面寫出來.// 注意,在子模版中,按鈕的綁定使用的是@而不是:let vm = new Vue({el:"#app",methods:{sayConnect(){console.log('connect success!');},sayBuild(){console.log('build success');}}});
</script>
接下來,看個更復雜一點的例子:
假設我們希望:
點擊"+1",總數加1;點擊"-1"總數減1. 且數據是來自子組件…
首先寫html
<div id = "app"><p>總數 {{ total }} </p><my-component @increase="handleTotal" @reduce="handleTotal"> </div>
</div>
// 說明: total 是父元素的
// @increase 對應 子組件中的 $emit('increase', data);
// @reduce 對應 子組件中的 @emit('reduce', data);
// handleTotal對應父組件中methods方法中的 handleTotal方法
掛載Vue,注冊組件
<script>// 組件應該在vue掛載之前注冊Vue.component('my-component',{ // 第一個參數組件名,對應html中的<my-component></my-component>// 首先寫替換<my-component>的templatetemplate:'\<div>\<button @click = "handleIncrease"> +1 </button>\<button @click = "handleReduce">-1 </button>\<div>',// ps: template中 寫了2個點擊事件 handleIncrease 和 handleReduce , 由于要傳一個數據給父元素,我們定義如下:data: function (){return {counter: 0;}}, // 子元素中的counter 初始化為0methods: {handleIncrease: function() {this.counter++;this.$emit('increase', this.counter);},handlerReduce: function() {this.counter--;this.$emit('reduce', this.counter);}}}); // 子模塊完畢// 說明: $emit(a,data)用來像父元素傳遞信息, 父元素用@'a'的形式接受信息// 開始掛載vue(在此是父元素).var app = new Vue({el: '#app',data: {total: 0 // 對應html <p>{{total}} </p>},methods:{handleTotal: function (total ){ // total 參數來自于 $emit的第二個參數..this.total = total; }}})</script>