vue是數據驅動視圖更新的框架, 所以對於vue來說組件間的數據通信非常重要,那麼組件之間如何進行數據通信的呢? 首先我們需要知道在vue中組件之間存在什麼樣的關係, 才更容易理解他們的通信方式, 就好像過年回家,坐著一屋子的陌生人,相互之間怎麼稱呼,這時就需要先知道自己和他們之間是什麼樣的關係。 ...
如上圖所示, A與B、A與C、B與D、C與E組件之間是父子關係; B與C之間是兄弟關係;A與D、A與E之間是隔代關係; D與E是堂兄關係(非直系親屬) 針對以上關係我們歸類為:
-
父子組件之間通信
-
非父子組件之間通信(兄弟組件、隔代關係組件等)
本文會介紹組件間通信的8種方式如下圖目錄所示:並介紹在不同的場景下如何選擇有效方式實現的組件間通信方式,希望可以幫助小伙伴們更好理解組件間的通信。
一、props
/ $emit
父組件通過props
的方式向子組件傳遞數據,而通過$emit
子組件可以向父組件通信。
1. 父組件向子組件傳值
下麵通過一個例子說明父組件如何向子組件傳遞數據:在子組件article.vue
中如何獲取父組件section.vue
中的數據articles:['紅樓夢', '西游記','三國演義']
// section父組件
<template>
<div class="section">
<com-article :articles="articleList"></com-article>
</div>
</template>
<script>
import comArticle from './test/article.vue'
export default {
name: 'HelloWorld',
components: { comArticle },
data() {
return {
articleList: ['紅樓夢', '西游記', '三國演義']
}
}
}
</script>
複製代碼
// 子組件 article.vue
<template>
<div>
<span v-for="(item, index) in articles" :key="index">{{item}}</span>
</div>
</template>
<script>
export default {
props: ['articles']
}
</script>
總結: prop 只可以從上一級組件傳遞到下一級組件(父子組件),即所謂的單向數據流。而且 prop 只讀,不可被修改,所有修改都會失效並警告。
2. 子組件向父組件傳值
對於$emit
我自己的理解是這樣的: $emit
綁定一個自定義事件, 當這個語句被執行時, 就會將參數arg傳遞給父組件,父組件通過v-on監聽並接收參數。 通過一個例子,說明子組件如何向父組件傳遞數據。 在上個例子的基礎上, 點擊頁面渲染出來的ariticle
的item
, 父組件中顯示在數組中的下標
// 父組件中
<template>
<div class="section">
<com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
<p>{{currentIndex}}</p>
</div>
</template>
<script>
import comArticle from './test/article.vue'
export default {
name: 'HelloWorld',
components: { comArticle },
data() {
return {
currentIndex: -1,
articleList: ['紅樓夢', '西游記', '三國演義']
}
},
methods: {
onEmitIndex(idx) {
this.currentIndex = idx
}
}
}
</script>
<template>
<div>
<div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div>
</div>
</template>
<script>
export default {
props: ['articles'],
methods: {
emitIndex(index) {
this.$emit('onEmitIndex', index)
}
}
}
</script>
二、 $children
/ $parent
上面這張圖片是vue``$parent``$children``data
使用方法
// 父組件中
<template>
<div class="hello_world">
<div>{{msg}}</div>
<com-a></com-a>
<button @click="changeA">點擊改變子組件值</button>
</div>
</template>
<script>
import ComA from './test/comA.vue'
export default {
name: 'HelloWorld',
components: { ComA },
data() {
return {
msg: 'Welcome'
}
},
methods: {
changeA() {
// 獲取到子組件A
this.$children[0].messageA = 'this is new value'
}
}
}
</script>
複製代碼
// 子組件中
<template>
<div class="com_a">
<span>{{messageA}}</span>
<p>獲取父組件的值為: {{parentVal}}</p>
</div>
</template>
<script>
export default {
data() {
return {
messageA: 'this is old'
}
},
computed:{
parentVal(){
return this.$parent.msg;
}
}
}
</script>
要註意邊界情況,如在
#app
上拿$parent
得到的是new Vue()
的實例,在這實例上再拿$parent
得到的是undefined
,而在最底層的子組件拿$children
是個空數組。也要註意得到$parent
和$children
的值不一樣,$children
的值是數組,而$parent
是個對象
總結
上面兩種方式用於父子組件之間的通信, 而使用props進行父子組件通信更加普遍; 二者皆不能用於非父子組件之間的通信。
三、provide
/ inject
概念:
provide
/ inject
是vue2.2.0
新增的api, 簡單來說就是父組件中通過provide
來提供變數, 然後再子組件中通過inject
來註入變數。
註意: 這裡不論子組件嵌套有多深, 只要調用了
inject
那麼就可以註入provide
中的數據,而不局限於只能從當前父組件的props屬性中回去數據
舉例驗證
接下來就用一個例子來驗證上面的描述: 假設有三個組件: A.vue、B.vue、C.vue 其中 C是B的子組件,B是A的子組件
// A.vue
<template>
<div>
<comB></comB>
</div>
</template>
<script>
import comB from '../components/test/comB.vue'
export default {
name: "A",
provide: {
for: "demo"
},
components:{
comB
}
}
</script>
複製代碼
// B.vue
<template>
<div>
{{demo}}
<comC></comC>
</div>
</template>
<script>
import comC from '../components/test/comC.vue'
export default {
name: "B",
inject: ['for'],
data() {
return {
demo: this.for
}
},
components: {
comC
}
}
</script>
複製代碼
// C.vue
<template>
<div>
{{demo}}
</div>
</template>
<script>
export default {
name: "C",
inject: ['for'],
data() {
return {
demo: this.for
}
}
}
</script>
四、ref
/ refs
ref
:如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向組件實例,可以通過實例直接調用組件的方法或訪問數據, 我們看一個ref
來訪問組件的例子:
// 子組件 A.vue
export default {
data () {
return {
name: 'Vue.js'
}
},
methods: {
sayHello () {
console.log('hello')
}
}
}
複製代碼
// 父組件 app.vue
<template>
<component-a ref="comA"></component-a>
</template>
<script>
export default {
mounted () {
const comA = this.$refs.comA;
console.log(comA.name); // Vue.js
comA.sayHello(); // hello
}
}
</script>
五、eventBus
eventBus
又稱為事件匯流排,在vue中可以使用它來作為溝通橋梁的概念, 就像是所有組件共用相同的事件中心,可以向該中心註冊發送事件或接收事件, 所以組件都可以通知其他組件。
eventBus也有不方便之處, 當項目較大,就容易造成難以維護的災難
在Vue的項目中怎麼使用eventBus
來實現組件之間的數據通信呢?具體通過下麵幾個步驟
1. 初始化
首先需要創建一個事件匯流排並將其導出, 以便其他模塊可以使用或者監聽它.
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
2. 發送事件
假設你有兩個組件: additionNum
和 showNum
, 這兩個組件可以是兄弟組件也可以是父子組件;這裡我們以兄弟組件為例:
<template>
<div>
<show-num-com></show-num-com>
<addition-num-com></addition-num-com>
</div>
</template>
<script>
import showNumCom from './showNum.vue'
import additionNumCom from './additionNum.vue'
export default {
components: { showNumCom, additionNumCom }
}
</script>
複製代碼
// addtionNum.vue 中發送事件
<template>
<div>
<button @click="additionHandle">+加法器</button>
</div>
</template>
<script>
import {EventBus} from './event-bus.js'
console.log(EventBus)
export default {
data(){
return{
num:1
}
},
methods:{
additionHandle(){
EventBus.$emit('addition', {
num:this.num++
})
}
}
}
</script>
3. 接收事件
// showNum.vue 中接收事件
<template>
<div>計算和: {{count}}</div>
</template>
<script>
import { EventBus } from './event-bus.js'
export default {
data() {
return {
count: 0
}
},
mounted() {
EventBus.$on('addition', param => {
this.count = this.count + param.num;
})
}
}
</script>
這樣就實現了在組件addtionNum.vue
中點擊相加按鈕, 在showNum.vue
中利用傳遞來的 num
展示求和的結果.
4. 移除事件監聽者
如果想移除事件的監聽, 可以像下麵這樣操作:
import { eventBus } from 'event-bus.js'
EventBus.$off('addition', {})
六、Vuex
1. Vuex介紹
Vuex 是一個專為 Vue.js 應用程式開發的狀態管理模式。它採用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化. Vuex 解決了多個視圖依賴於同一狀態
和來自不同視圖的行為需要變更同一狀態
的問題,將開發者的精力聚焦於數據的更新而不是數據在組件之間的傳遞上
2. Vuex各個模塊
-
state
:用於數據的存儲,是store中的唯一數據源 -
getters
:如vue中的計算屬性一樣,基於state數據的二次包裝,常用於數據的篩選和多個數據的相關性計算 -
mutations
:類似函數,改變state數據的唯一途徑,且不能用於處理非同步事件 -
actions
:類似於mutation
,用於提交mutation
來改變狀態,而不直接變更狀態,可以包含任意非同步操作 -
modules
:類似於命名空間,用於項目中將各個模塊的狀態分開定義和操作,便於維護
3. Vuex實例應用
// 父組件
<template>
<div id="app">
<ChildA/>
<ChildB/>
</div>
</template>
<script>
import ChildA from './components/ChildA' // 導入A組件
import ChildB from './components/ChildB' // 導入B組件
export default {
name: 'App',
components: {ChildA, ChildB} // 註冊A、B組件
}
</script>
複製代碼
// 子組件childA
<template>
<div id="childA">
<h1>我是A組件</h1>
<button @click="transform">點我讓B組件接收到數據</button>
<p>因為你點了B,所以我的信息發生了變化:{{BMessage}}</p>
</div>
</template>
<script>
export default {
data() {
return {
AMessage: 'Hello,B組件,我是A組件'
}
},
computed: {
BMessage() {
// 這裡存儲從store里獲取的B組件的數據
return this.$store.state.BMsg
}
},
methods: {
transform() {
// 觸發receiveAMsg,將A組件的數據存放到store里去
this.$store.commit('receiveAMsg', {
AMsg: this.AMessage
})
}
}
}
</script>
複製代碼
// 子組件 childB
<template>
<div id="childB">
<h1>我是B組件</h1>
<button @click="transform">點我讓A組件接收到數據</button>
<p>因為你點了A,所以我的信息發生了變化:{{AMessage}}</p>
</div>
</template>
<script>
export default {
data() {
return {
BMessage: 'Hello,A組件,我是B組件'
}
},
computed: {
AMessage() {
// 這裡存儲從store里獲取的A組件的數據
return this.$store.state.AMsg
}
},