您好,登錄后才能下訂單哦!
這篇文章主要講解了“vue3組件通信方式有哪些”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“vue3組件通信方式有哪些”吧!
面試題經(jīng)常會問到vue3組件間的通信方式,下文列舉了七種常見的通信方式。
props
emit
v-model
refs
provide/inject
eventBus
Vuex4/pinia(vuex5)
父組件以數(shù)據(jù)綁定的形式聲明要傳遞的數(shù)據(jù),子組件通過defineProperty()方法創(chuàng)建props對象,即可拿到父組件傳來的數(shù)據(jù)。
父組件的template中:
<!-- list是我們要傳遞的數(shù)據(jù) --> <child-components :list="list"></child-components>
子組件:
<template> <ul> <li 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
方式也是Vue中最常見的組件通信方式,該方式用于子傳父;
父組件的template中:
<!-- add是子組件要傳遞的動作,handleAdd是監(jiān)聽到之后執(zhí)行的事件 --> <child-components @add="handleAdd"></child-components> <script> const list = ref([1,2,3]) const handleAdd = value => { list.value.push(value) } </script>
子組件中:
const emits = defineEmits(['add']) emits('add', 1)
v-model不能嚴(yán)格成為數(shù)據(jù)的傳遞方式,其實(shí)只是減少了代碼量。
<ChildComponent v-model:list="list" /> // 等價(jià)于 <ChildComponent :list="pageTitle" @update:list="list = $event" />
子組件需要emit一個(gè)叫update:xxx的事件,再把需要更新的響應(yīng)式數(shù)據(jù)傳給emit方法的第二個(gè)參數(shù)即可,如:
const emits = defineEmits(['update:list']) emits('update:list', arr)
有時(shí)候想訪問 r e f s 綁 定 的 組 件 的 屬 性 或 者 方 法 , 我 們 會 使 用 refs綁定的組件的屬性或者方法,我們會使用 refs綁定的組件的屬性或者方法,我們會使用refs。但是Vue3不同于Vue2,在 Vue3的setup中我們是無法訪問到this的,所以我們需要借助一個(gè)方法,那就是getCurrentInstance,該方法返回了當(dāng)前的實(shí)例對象。
父組件如下:
<template> <div> <Child ref="child"></Child> <button @click="show">Show Child Message</button> </div> </template> <script setup> import { getCurrentInstance } from '@vue/runtime-core'; import Child from './Child.vue'; const currentInstance = getCurrentInstance() function show() { currentInstance.$refs.child.alertMessage() } </script>
子組件代碼如下:
<template> <div> <h2>{{ message }}</h2> </div> </template> <script setup> import { ref } from '@vue/reactivity'; let message = ref('我是子元素').value const alertMessage = function () { alert(message) } defineExpose({ message, alertMessage }) </script>
注意??,通過<script setup>
語法糖的寫法,其組件是默認(rèn)關(guān)閉的,也就是說如果是通過$refs
或者$parents
來訪問子組件中定義的值是拿不到的,必須通過defineExpose向外暴露你想獲取的值才行。
provide/inject是 Vue 中提供的一對 API。無論層級多深,API 都可以實(shí)現(xiàn)父組件到子孫組件的數(shù)據(jù)傳遞。
// 父組件中 provide('list', list.value) // 子組件中 const list = inject('list')
Vue 3 中移除了 eventBus,但可以借助第三方工具來完成。Vue 官方推薦使用 mitt 或 tiny-emitter。
Vuex 和 Pinia 是 Vue 3 中的狀態(tài)管理工具,使用這兩個(gè)工具可以輕松實(shí)現(xiàn)組件通信。
感謝各位的閱讀,以上就是“vue3組件通信方式有哪些”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對vue3組件通信方式有哪些這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。