vue中組件常用傳值方式

.1 父子組件間傳值

  • 父組件給子組件傳值,直接通過props傳值
<custom content="hello world"></custom>
複製代碼
  • 子組件給父組件傳值,通過 emit發送事件
this.$emit('chooseType', type)
複製代碼

父組件接收事件:

<custom content="hello world" @chooseType="handleType"></custom>
複製代碼

6.2 非父子組件傳值

主要通過事件總線傳值

在根節點給 Vue 掛載一個空的 Vue 對象

Vue.prototype.bus = new Vue();

需要發送事件的組件裏

this.bus.$emit("change", params)

接收事件的組件

this.bus.$on("change", (msg) => {
    //do yourself work
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章