原文鏈接 : 7個 Vue3 中的組件通信方式
01.png
前言
本文采用<script setup />的編寫方式,比options API更自由。然后我們會講以下七種組件通信方式:
- props
- emit
- v-model
- refs
- provide/inject
- eventBus
- vuex/pinia
舉個例子
本文將使用如下演示,如下圖所示:

上圖中,列表和輸入框分別是父組件和子組件。根據(jù)不同的通信方式,會調(diào)整父子組件。
Props
props 是 Vue 中最常見的父子通信方式,使用起來也比較簡單。
根據(jù)上面的demo,我們在父組件中定義了數(shù)據(jù)和對數(shù)據(jù)的操作,子組件只渲染一個列表。
父組件代碼如下:
<template>
<!-- child component -->
<child-components :list="list"></child-components>
<!-- parent component -->
<div class="child-wrap input-group">
<input
v-model="value"
type="text"
class="form-control"
placeholder="Please enter"
/>
<div class="input-group-append">
<button @click="handleAdd" class="btn btn-primary" type="button">
add
</button>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import ChildComponents from './child.vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])
const value = ref('')
// event handling function triggered by add
const handleAdd = () => {
list.value.push(value.value)
value.value = ''
}
</script>
子組件只需要渲染父組件傳遞的值。
代碼如下:
<template>
<ul class="parent list-group">
<li class="list-group-item" v-for="i in props.list" :key="i">{{ i }}</li>
</ul>
</template>
<script setup>
import { defineProps } from 'vue'
const props = defineProps({
list: {
type: Array,
default: () => [],
},
})
</script>
Emit
Emit也是Vue中最常見的組件通信方式,用于子組件向父組件傳遞消息。
我們在父組件中定義列表,子組件只需要傳遞添加的值。
子組件代碼如下:
<template>
<div class="child-wrap input-group">
<input
v-model="value"
type="text"
class="form-control"
placeholder="Please enter"
/>
<div class="input-group-append">
<button @click="handleSubmit" class="btn btn-primary" type="button">
add
</button>
</div>
</div>
</template>
<script setup>
import { ref, defineEmits } from 'vue'
const value = ref('')
const emits = defineEmits(['add'])
const handleSubmit = () => {
emits('add', value.value)
value.value = ''
}
</script>
點擊子組件中的【添加】按鈕后,我們會發(fā)出一個自定義事件,并將添加的值作為參數(shù)傳遞給父組件。
父組件代碼如下:
<template>
<!-- parent component -->
<ul class="parent list-group">
<li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>
</ul>
<!-- child component -->
<child-components @add="handleAdd"></child-components>
</template>
<script setup>
import { ref } from 'vue'
import ChildComponents from './child.vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])
// event handling function triggered by add
const handleAdd = value => {
list.value.push(value)
}
</script>
在父組件中,只需要監(jiān)聽子組件的自定義事件,然后執(zhí)行相應(yīng)的添加邏輯即可。
v-model
v-model是Vue中一個優(yōu)秀的語法糖,比如下面的代碼。
<ChildComponent v-model:title="pageTitle" />
這是以下代碼的簡寫形式
<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />
這確實容易了很多?,F(xiàn)在我們將使用v-model來實現(xiàn)上面的示例。
子組件代碼如下:
<template>
<div class="child-wrap input-group">
<input
v-model="value"
type="text"
class="form-control"
placeholder="Please enter"
/>
<div class="input-group-append">
<button @click="handleAdd" class="btn btn-primary" type="button">
add
</button>
</div>
</div>
</template>
<script setup>
import { ref, defineEmits, defineProps } from 'vue'
const value = ref('')
const props = defineProps({
list: {
type: Array,
default: () => [],
},
})
const emits = defineEmits(['update:list'])
// Add action
const handleAdd = () => {
const arr = props.list
arr.push(value.value)
emits('update:list', arr)
value.value = ''
}
</script>
在子組件中,我們先定義props和emits,添加完成后再發(fā)出指定的事件。
注意:update:
*是Vue中固定的寫法,*代表props中的一個屬性名。
在父組件中使用比較簡單,代碼如下:
<template>
<!-- parent component -->
<ul class="parent list-group">
<li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>
</ul>
<!-- child component -->
<child-components v-model:list="list"></child-components>
</template>
<script setup>
import { ref } from 'vue'
import ChildComponents from './child.vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])
</script>
Refs
使用API選項時,我們可以通過this.$refs.name獲取指定的元素或組件,但在組合API中不行。如果我們想通過ref獲取,需要定義一個同名的Ref對象,在組件掛載后可以訪問。
示例代碼如下:
<template>
<ul class="parent list-group">
<li class="list-group-item" v-for="i in childRefs?.list" :key="i">
{{ i }}
</li>
</ul>
<!-- The value of the child component ref is the same as that in the <script> -->
<child-components ref="childRefs"></child-components>
<!-- parent component -->
</template>
<script setup>
import { ref } from 'vue'
import ChildComponents from './child.vue'
const childRefs = ref(null)
</script>
子組件代碼如下:
<template>
<div class="child-wrap input-group">
<input
v-model="value"
type="text"
class="form-control"
placeholder="Please enter"
/>
<div class="input-group-append">
<button @click="handleAdd" class="btn btn-primary" type="button">
add
</button>
</div>
</div>
</template>
<script setup>
import { ref, defineExpose } from 'vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])
const value = ref('')
// event handling function triggered by add
const handleAdd = () => {
list.value.push(value.value)
value.value = ''
}
defineExpose({ list })
</script>
注意:默認情況下,
setup組件是關(guān)閉的,通過模板ref獲取組件的公共實例。如果需要公開,需要通過defineExpose API公開。
provide/inject
provide/inject是 Vue 中提供的一對 API。無論層級多深,API 都可以實現(xiàn)父組件到子組件的數(shù)據(jù)傳遞。
父組件代碼如下所示:
<template>
<!-- child component -->
<child-components></child-components>
<!-- parent component -->
<div class="child-wrap input-group">
<input
v-model="value"
type="text"
class="form-control"
placeholder="Please enter"
/>
<div class="input-group-append">
<button @click="handleAdd" class="btn btn-primary" type="button">
add
</button>
</div>
</div>
</template>
<script setup>
import { ref, provide } from 'vue'
import ChildComponents from './child.vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])
const value = ref('')
// Provide data to child components.
provide('list', list.value)
// event handling function triggered by add
const handleAdd = () => {
list.value.push(value.value)
value.value = ''
}
</script>
子組件代碼如下所示:
<template>
<ul class="parent list-group">
<li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>
</ul>
</template>
<script setup>
import { inject } from 'vue'
// Accept data provided by parent component
const list = inject('list')
</script>
注意:使用
provide進行數(shù)據(jù)傳輸時,盡量使用readonly封裝數(shù)據(jù),避免子組件修改父組件傳遞的數(shù)據(jù)。
eventBus
Vue3 中移除了eventBus,但可以借助第三方工具來完成。Vue 官方推薦使用mitt或tiny-emitter。
在大多數(shù)情況下,不建議使用全局事件總線來實現(xiàn)組件通信。雖然比較簡單粗暴,但是維護事件總線從長遠來看是個大問題,這里就不解釋了。有關(guān)詳細信息,您可以閱讀特定工具的文檔。
7、vuex/pinia
Vuex和Pinia是 Vue3 中的狀態(tài)管理工具,使用這兩個工具可以輕松實現(xiàn)組件通信。由于這兩個工具都比較強大,這里就不一一展示了。有關(guān)詳細信息,請參閱文檔。
