Vue元件之間通訊,父到子,子到父,非父子元件之間資料傳遞梳理
一、父元件=》子元件傳遞資料
1、子元件在props中建立一個屬性,用以接收父元件傳過來的值
2、父元件中註冊子元件
3、在子元件標籤中新增子元件props中建立的屬性
4、把需要傳給子元件的值賦給該屬性
二、子元件=》父元件傳遞資料
*當子元件需要向父元件傳遞資料時,就要用到自定義事件。
1、子元件中需要以某種方式例如點選事件的方法來觸發一個自定義事件
2、將需要傳的值作為$emit的第二個引數,該值將作為實參傳給響應自定義事件的方法
3、在父元件中註冊子元件並在子元件標籤上繫結對自定義事件的監聽
三、非父子元件傳遞資料
1、新建一個eventBus.js檔案,在裡面新建一個vue例項,這個例項就承擔起了元件之間通訊的橋樑了,也就是中央事件匯流排
2、然後給每個子元件繫結一個方法(觸發時候釋出eventBus),在每個子元件做一個訂閱的監控,觸發綁在created裡的方法執行
在通訊中,元件之間傳值,他們都有一個共同點就是有中間介質,
*子向父的介質是自定義事件
*父向子的介質是props中的屬性
*非父子元件的介質是中央事件匯流排抓準這三點對於元件之間通訊就好理解了
vue-cli建立的專案,附上精簡的程式碼與圖片:
HelloWorld.vue
<template> <div class="hello"> <h1>hello標題</h1> <!-- // 在子元件標籤child-aa上繫結myEvent對自定義事件的監聽 --> <child-aa :myProp="toChildA" @myEvent="touchMe"></child-aa> <div>孩子,你貴姓:{{getByChildA}}</div> <child-bcd :myProp="toChildA" @myEvent="touchMe"></child-bcd> </div> </template> <script> import childAa from './childA' import childBcd from './childBcd' export default { name: 'HelloWorld', data () { return { toChildA: '給子元件childA傳字串內容', // 把需要傳給子元件的值賦給該屬性 getByChildA: '' } }, components: { childAa, // 父元件中註冊子元件 childBcd }, methods: { touchMe(obj) { this.getByChildA = obj.age } } } </script>
childA.vue
<template> <div class="childA"> <h3>這裡是childA</h3> <div> {{myProp}} </div> <button @click="doSomething"> 給父元件傳個資訊 </button> <h3>兄弟元件傳什麼過來了:{{brotherInfo}}</h3> </div> </template> <script> import $bus from '../untils/eventBus' export default { name: 'childA', data () { return { brotherInfo: '' } }, props: { myProp: { type: String // 子元件在props中建立一個屬性,用以接收父元件傳過來的值 } }, methods: { doSomething() { // 子元件中需要以某種方式例如點選事件的方法來觸發一個自定義事件 this.$emit('myEvent', {age: 'lihongwei'}) // 將需要傳的值作為$emit的第二個引數,該值將作為實參傳給響應自定義事件的方法 } }, created() { $bus.$on('myEvent',(brotherInfo) => { this.brotherInfo = brotherInfo }) } } </script> <style scoped> .childA{ padding: 30px; border: 5px solid #ddd; } </style>
childBcd.vue
<template> <div class="childBcd"> <h3>這裡是childBcd</h3> <button @click="toBrother"> 給chidA傳個資訊 </button> </div> </template> <script> import $bus from '../untils/eventBus' export default { name: 'childBcd', data () { return { } }, methods: { toBrother() { $bus.$emit('myEvent', '兄弟,你好') } } } </script> <style scoped> .childBcd{ padding: 30px; border: 5px solid #ddd; } </style>
eventBus.js
import Vue from 'vue' export default new Vue()