總結了 Vue3 的七種組件通信方式,別再說不會組件通信了
寫在前面
本篇文章是全部採用的<script setup>
這種組合式 API 寫法,相對於選項式來說,組合式 API 這種寫法更加自由,具體可以參考 Vue 文檔對兩種方式的描述。本篇文章將介紹如下七種組件通信方式:
-
props
-
emit
-
v-model
-
refs
-
provide/inject
-
eventBus
-
vuex/pinia(狀態管理工具)
開始搞事情~
舉一個栗子
俗話說的好,學習不寫 demo,那就是耍流氓~
本篇文章將圍繞下面這個 demo,如下圖所示:
上圖中,列表和輸入框分別是父子組件,根據不同傳值方式,可能誰是父組件誰是子組件會有所調整。
Props 方式
Props
方式是 Vue 中最常見的一種父傳子的一種方式,使用也比較簡單。
根據上面的 demo,我們將數據以及對數據的操作定義在父組件,子組件僅做列表的一個渲染;
父組件代碼如下:
<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 觸發後的事件處理函數
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 poops.list" :key="i">{{ i }}</li>
</ul>
</template>
<script setup>
import { defineProps } from 'vue'
const poops = defineProps({
list: {
type: Array,
default: () => [],
},
})
</script>
emit 方式
emit
方式也是 Vue 中最常見的組件通信方式,該方式用於子傳父
;
根據上面的 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 一個自定義事件,並將添加的值作爲參數傳遞。
父組件代碼如下:
<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 觸發後的事件處理函數
const handleAdd = value => {
list.value.push(value)
}
</script>
在父組件中只需要監聽子組件自定義的事件,然後執行對應的添加操作。
v-model 方式
v-model
是 Vue 中一個比較出色的語法糖,就比如下面這段代碼
<ChildComponent v-model:title="pageTitle" />
就是下面這段代碼的簡寫形勢
<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />
v-model
確實簡便了不少,現在我們就來看一下上面那個 demo,如何用 v-model 實現。
子組件
<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 觸發後的事件處理函數
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 可以實現父組件向子組件傳遞數據,無論層級有多深,都可以通過這對 API 實現。示例代碼如下所示:
父組件
<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('')
// 向子組件提供數據
provide('list', list.value)
// 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'
// 接受父組件提供的數據
const list = inject('list')
</script>
事件總線
Vue3 中移除了事件總線,但是可以藉助於第三方工具來完成,Vue 官方推薦mitt
或tiny-emitter
;在大多數情況下不推薦使用全局事件總線的方式來實現組件通信,雖然比較簡單粗暴,但是長久來說維護事件總線是一個大難題,所以這裏就不展開講解了,具體可以閱讀具體工具的文檔。
狀態管理工具
Vuex
和Pinia
是 Vue3 中的狀態管理工具,使用這兩個工具可以輕鬆實現組件通信,由於這兩個工具功能比較強大,這裏就不做展示了,具體可以查閱文檔
寫在最後
本篇文章到這就結束了,總的來說比較簡單,沒有什麼複雜內容。
如果這篇文章對你來說有點作用,歡迎點贊、評論、收藏,避免在需要的時候找不到。
如果文中有錯誤,歡迎指正~
文章來自掘金 @一碗周,https://juejin.cn/post/7062740057018335245
最後
也許你我素未謀面,但很可能相見恨晚。希望這裏能成爲你的棲息之地,我願和你一起收穫喜悅,奔赴成長。
期待你關注「前端胖頭魚」,回覆「交流」加入前端編程面試算法羣,助力你成爲更優秀的前端開發!
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/8a5MFDjh_Khb_m-wRkzNOg