Vue 組件通訊

父組件 -> 子組件html

props vue

<my-component :date="date"></my-component>

注意:若是子組件定義props名稱使用了駝峯命名,則須要在傳值時改爲 - 分開,由於html對大小寫不敏感,例如vuex

<my-component :my-date="date"></my-component>

* 可是在vue單文件組件中貌似是能夠使用駝峯寫法的框架

 

子組件 -> 父組件this

子組件中直接修改props值能夠成功,可是框架會拋出一個錯誤,因此不推薦spa

推薦的作法:在父組件中定義一個修改props的方法,而後子組件調用父組件的方法prototype

1. 在子組件中直接調用父組件方法修改props值code

this.$parent.change(new Date())

2. 子組件觸發事件,在父組件中捕捉而後執行change方法component

父組件:htm

<my-component :my-date="date" @changeDate="change"></my-component>

子組件:

this.$emit('changeDate', new Date())

推薦使用第二種

 

子組件 -> 子組件

這種狀況屬於兩個不相關的子組件之間的通訊,咱們沒法經過props將二者關聯起來,兩種解決辦法:

1. vuex : 全局狀態管理器

2. 事件總線:EventBus

定義:本質上就是實例化一個新的Vue對象,這個對象專門負責處理多組件之間的通訊

用法:

// main.js
Vue.prototype.$EventBus = new Vue()

綁定一個eventBus到Vue對象,在頁面中經過 on(註冊),emit(觸發)

//component1
this.$EventBus.$on('change', function(param){
  console.log('事件觸發',param)
})
//component2
this.$EventBus.$emit('change', 123)
相關文章
相關標籤/搜索