7個(gè) Vue3 中的組件通信方式

原文鏈接 :??https://fe32.top/articles/vu9856es/

前言
本文采用<script setup />
的編寫方式,比options API
更自由。然后我們會(huì)講以下七種組件通信方式:
props
emit
v-model
refs
provide/inject
eventBus
vuex/pinia
舉個(gè)例子
本文將使用如下演示,如下圖所示:?

?上圖中,列表和輸入框分別是父組件和子組件。根據(jù)不同的通信方式,會(huì)調(diào)整父子組件。
Props
props 是 Vue 中最常見的父子通信方式,使用起來也比較簡(jiǎn)單。
根據(jù)上面的demo,我們?cè)诟附M件中定義了數(shù)據(jù)和對(duì)數(shù)據(jù)的操作,子組件只渲染一個(gè)列表。
父組件代碼如下:
JavaScript
<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 addconst handleAdd = () => { ?list.value.push(value.value) ?value.value = ''}</script>
子組件只需要渲染父組件傳遞的值。
代碼如下:
JavaScript
<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
中最常見的組件通信方式,用于子組件向父組件傳遞消息。
我們?cè)诟附M件中定義列表,子組件只需要傳遞添加的值。
子組件代碼如下:
JavaScript
<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>
點(diǎn)擊子組件中的【添加】按鈕后,我們會(huì)發(fā)出一個(gè)自定義事件,并將添加的值作為參數(shù)傳遞給父組件。
父組件代碼如下:
JavaScript
<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 addconst handleAdd = value => { ?list.value.push(value)}</script>
在父組件中,只需要監(jiān)聽子組件的自定義事件,然后執(zhí)行相應(yīng)的添加邏輯即可。
v-model
v-model
是Vue
中一個(gè)優(yōu)秀的語(yǔ)法糖,比如下面的代碼。
HTML
<ChildComponent v-model:title="pageTitle" />
這是以下代碼的簡(jiǎn)寫形式
HTML
<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />
這確實(shí)容易了很多。現(xiàn)在我們將使用v-model
來實(shí)現(xiàn)上面的示例。
子組件代碼如下:
JavaScript
<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 actionconst handleAdd = () => { ?const arr = props.list ?arr.push(value.value) ?emits('update:list', arr) ?value.value = ''}</script>
在子組件中,我們先定義props
和emits
,添加完成后再發(fā)出指定的事件。
注意:update:
*
是Vue
中固定的寫法,*
代表props
中的一個(gè)屬性名。
在父組件中使用比較簡(jiǎn)單,代碼如下:
JavaScript
<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選項(xiàng)時(shí),我們可以通過this.$refs.name
獲取指定的元素或組件,但在組合API中不行。如果我們想通過ref
獲取,需要定義一個(gè)同名的Ref
對(duì)象,在組件掛載后可以訪問。
示例代碼如下:
JavaScript
<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>
子組件代碼如下:
JavaScript
<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 addconst handleAdd = () => { ?list.value.push(value.value) ?value.value = ''}defineExpose({ list })</script>
注意:默認(rèn)情況下,
setup
組件是關(guān)閉的,通過模板ref
獲取組件的公共實(shí)例。如果需要公開,需要通過defineExpose API
公開。
provide/inject
provide/inject
是 Vue 中提供的一對(duì) API。無論層級(jí)多深,API 都可以實(shí)現(xiàn)父組件到子組件的數(shù)據(jù)傳遞。
父組件代碼如下所示:
JavaScript
<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 addconst handleAdd = () => { ?list.value.push(value.value) ?value.value = ''}</script>
子組件代碼如下所示:
JavaScript
<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 componentconst list = inject('list')</script>
注意:使用
provide
進(jìn)行數(shù)據(jù)傳輸時(shí),盡量使用readonly
封裝數(shù)據(jù),避免子組件修改父組件傳遞的數(shù)據(jù)。
eventBus
Vue3 中移除了eventBus
,但可以借助第三方工具來完成。Vue 官方推薦使用mitt
或tiny-emitter
。
在大多數(shù)情況下,不建議使用全局事件總線來實(shí)現(xiàn)組件通信。雖然比較簡(jiǎn)單粗暴,但是維護(hù)事件總線從長(zhǎng)遠(yuǎn)來看是個(gè)大問題,這里就不解釋了。有關(guān)詳細(xì)信息,您可以閱讀特定工具的文檔。
7、vuex/pinia
Vuex
和Pinia
是 Vue3 中的狀態(tài)管理工具,使用這兩個(gè)工具可以輕松實(shí)現(xiàn)組件通信。由于這兩個(gè)工具都比較強(qiáng)大,這里就不一一展示了。有關(guān)詳細(xì)信息,請(qǐng)參閱文檔。