總結了Vue3的七種組件通信方式,別再說不會組件通信了
點擊上方 前端Q,關注公眾號
回復加群,加入前端Q技術交流群
寫在前面
本篇文章是全部采用的 <script setup> 這種組合式API寫法,相對于選項式來說,組合式API這種寫法更加自由,具體可以參考Vue文檔[1]對兩種方式的描述。
本篇文章將介紹如下七種組件通信方式:
-
props -
emit -
v-model -
refs -
provide/inject -
eventBus -
vuex/pinia(狀態(tài)管理工具)
開始搞事情~
舉一個栗子
俗話說的好,學習不寫demo,那就是耍流氓~
本篇文章將圍繞下面這個demo,如下圖所示:
上圖中,_列表_和_輸入框_分別是父子組件,根據(jù)不同傳值方式,可能誰是父組件誰是子組件會有所調(diào)整。
Props方式
Props方式是Vue中最常見的一種父傳子的一種方式,使用也比較簡單。
根據(jù)上面的demo,我們將數(shù)據(jù)以及對數(shù)據(jù)的操作定義在父組件,子組件僅做列表的一個渲染;
父組件代碼如下:
<template>
<!-- 子組件 -->
<child-components :list="list"></child-components>
<!-- 父組件 -->
<div class="child-wrap input-group">
<input
v-model="value"
type="text"
class="form-control"
placeholder="請輸入"
/>
<div class="input-group-append">
<button @click="handleAdd" class="btn btn-primary" type="button">
添加
</button>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import ChildComponents from './child.vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])
const value = ref('')
// add 觸發(fā)后的事件處理函數(shù)
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中最常見的組件通信方式,該方式用于子傳父;
根據(jù)上面的demo,我們將列表定義在父組件,子組件只需要傳遞添加的值即可。
子組件代碼如下:
<template>
<div class="child-wrap input-group">
<input
v-model="value"
type="text"
class="form-control"
placeholder="請輸入"
/>
<div class="input-group-append">
<button @click="handleSubmit" class="btn btn-primary" type="button">
添加
</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>
復制代碼
在子組件中點擊【添加】按鈕后,emit一個自定義事件,并將添加的值作為參數(shù)傳遞。
父組件代碼如下:
<template>
<!-- 父組件 -->
<ul class="parent list-group">
<li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>
</ul>
<!-- 子組件 -->
<child-components @add="handleAdd"></child-components>
</template>
<script setup>
import { ref } from 'vue'
import ChildComponents from './child.vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])
// add 觸發(fā)后的事件處理函數(shù)
const handleAdd = value => {
list.value.push(value)
}
</script>
復制代碼
在父組件中只需要監(jiān)聽子組件自定義的事件,然后執(zhí)行對應的添加操作。
v-model方式
v-model是Vue中一個比較出色的語法糖,就比如下面這段代碼
<ChildComponent v-model:title="pageTitle" />
復制代碼
就是下面這段代碼的簡寫形勢
<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />
復制代碼
v-model確實簡便了不少,現(xiàn)在我們就來看一下上面那個demo,如何用v-model實現(xiàn)。
子組件
<template>
<div class="child-wrap input-group">
<input
v-model="value"
type="text"
class="form-control"
placeholder="請輸入"
/>
<div class="input-group-append">
<button @click="handleAdd" class="btn btn-primary" type="button">
添加
</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'])
// 添加操作
const handleAdd = () => {
const arr = props.list
arr.push(value.value)
emits('update:list', arr)
value.value = ''
}
</script>
復制代碼
在子組件中我們首先定義props和emits,然后添加完成之后emit指定事件。
注:
update:*是Vue中的固定寫法,*表示props中的某個屬性名。
父組件中使用就比較簡單,代碼如下:
<template>
<!-- 父組件 -->
<ul class="parent list-group">
<li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>
</ul>
<!-- 子組件 -->
<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>
<!-- 子組件 ref的值與<script>中的保持一致 -->
<child-components ref="childRefs"></child-components>
<!-- 父組件 -->
</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="請輸入"
/>
<div class="input-group-append">
<button @click="handleAdd" class="btn btn-primary" type="button">
添加
</button>
</div>
</div>
</template>
<script setup>
import { ref, defineExpose } from 'vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])
const value = ref('')
// add 觸發(fā)后的事件處理函數(shù)
const handleAdd = () => {
list.value.push(value.value)
value.value = ''
}
defineExpose({ list })
</script>
復制代碼
setup組件默認是關閉的,也即通過模板ref獲取到的組件的公開實例,不會暴露任何在**<script setup>**中聲明的綁定。如果需要**公開需要通過****defineExpose**** API暴露**。
provide/inject方式
provide和inject是Vue中提供的一對API,該API可以實現(xiàn)父組件向子組件傳遞數(shù)據(jù),無論層級有多深,都可以通過這對API實現(xiàn)。示例代碼如下所示:
父組件
<template>
<!-- 子組件 -->
<child-components></child-components>
<!-- 父組件 -->
<div class="child-wrap input-group">
<input
v-model="value"
type="text"
class="form-control"
placeholder="請輸入"
/>
<div class="input-group-append">
<button @click="handleAdd" class="btn btn-primary" type="button">
添加
</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('')
// 向子組件提供數(shù)據(jù)
provide('list', list.value)
// add 觸發(fā)后的事件處理函數(shù)
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'
// 接受父組件提供的數(shù)據(jù)
const list = inject('list')
</script>
復制代碼
值得注意的是使用provide進行數(shù)據(jù)傳遞時,盡量readonly進行數(shù)據(jù)的包裝,避免子組件修改父級傳遞過去的數(shù)據(jù)。
事件總線
Vue3中移除了事件總線,但是可以借助于第三方工具來完成,Vue官方推薦mitt[2]或tiny-emitter[3];
在大多數(shù)情況下不推薦使用全局事件總線的方式來實現(xiàn)組件通信,雖然比較簡單粗暴,但是長久來說維護事件總線是一個大難題,所以這里就不展開講解了,具體可以閱讀具體工具的文檔
狀態(tài)管理工具
Vuex[4]和Pinia[5]是Vue3中的狀態(tài)管理工具,使用這兩個工具可以輕松實現(xiàn)組件通信,由于這兩個工具功能比較強大,這里就不做展示了,具體可以查閱文檔
寫在最后
本篇文章到這就結束了,總的來說比較簡單,沒有什么復雜內(nèi)容。
如果這篇文章對你來說有點作用,歡迎點贊、評論、收藏,避免在需要的時候找不到。
如果文中有錯誤,歡迎指正~
來自: 一碗周
https://juejin.cn/post/7062740057018335245
往期推薦
最后
歡迎加我微信,拉你進技術群,長期交流學習...
歡迎關注「前端Q」,認真學前端,做個專業(yè)的技術人...
