vue2自定義事件之$emit


父組件:

 

API上的解釋不多:

https://cn.vuejs.org/v2/api/#vm-emit

vm.$emit( event, […args] )

  • 參數:

    • {string} event
    • [...args]

    觸發當前實例上的事件。附加參數都會傳給監聽器回調。

  • Source

我們可以從組件的api中查看這個用法。

數據在組件中是單向流動的,當父組件的屬性變化時,將傳導給子組件,但是不會反過來。這是為了防止子組件無意修改了父組件的狀態——這會讓應用的數據流難以理解。《單向數據流

注意在 JavaScript 中對象和數組是引用類型,指向同一個內存空間,如果 prop 是一個對象或數組,在子組件內部改變它會影響父組件的狀態。

我們知道,父組件是使用 props 傳遞數據給子組件,但如果子組件要把數據傳遞回去,應該怎樣做?那就是自定義事件!

自定義事件

使用 v-on 綁定自定義事件

每個 Vue 實例都實現了事件接口(Events interface),即:

  • 使用 $on(eventName) 監聽事件
  • 使用 $emit(eventName) 觸發事件

Vue的事件系統分離自瀏覽器的EventTarget API。盡管它們的運行類似,但是$on 和 $emit 不是addEventListener 和 dispatchEvent 的別名。

另外,父組件可以在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件。

不能用$on偵聽子組件拋出的事件,而必須在模板里直接用v-on綁定,就像以下的例子:

下面是一個例子:

<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>


Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})

在本例中,子組件已經和它外部完全解耦了。它所做的只是報告自己的內部事件,至於父組件是否關心則與它無關。留意到這一點很重要。

給組件綁定原生事件

有時候,你可能想在某個組件的根元素上監聽一個原生事件。可以使用 .native 修飾 v-on 。例如:

<my-component v-on:click.native="doTheThing"></my-component>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM