老生常談vue3組件通信方式
vue3七種組件通信方式
面試題經(jīng)常會問到vue3組件間的通信方式,下文列舉了七種常見的通信方式。
- props
- emit
- v-model
- refs
- provide/inject
- eventBus
- Vuex4/pinia(vuex5)
1. Props方式
父組件以數(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>
注意在
2. emit方式
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)
3. v-model方式
v-model不能嚴格成為數(shù)據(jù)的傳遞方式,其實只是減少了代碼量。
<ChildComponent v-model:list="list" /> // 等價于 <ChildComponent :list="pageTitle" @update:list="list = $event" />
子組件需要emit一個叫update:xxx的事件,再把需要更新的響應式數(shù)據(jù)傳給emit方法的第二個參數(shù)即可,如:
const emits = defineEmits(['update:list']) emits('update:list', arr)
4、Refs
有時候想訪問 r e f s 綁 定 的 組 件 的 屬 性 或 者 方 法 , 我 們 會 使 用 refs綁定的組件的屬性或者方法,我們會使用 refs綁定的組件的屬性或者方法,我們會使用refs。但是Vue3不同于Vue2,在 Vue3的setup中我們是無法訪問到this的,所以我們需要借助一個方法,那就是getCurrentInstance,該方法返回了當前的實例對象。
父組件如下:
<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> <h1>{{ message }}</h1> </div> </template> <script setup> import { ref } from '@vue/reactivity'; let message = ref('我是子元素').value const alertMessage = function () { alert(message) } defineExpose({ message, alertMessage }) </script>
注意??,通過<script setup>
語法糖的寫法,其組件是默認關閉的,也就是說如果是通過$refs
或者$parents
來訪問子組件中定義的值是拿不到的,必須通過defineExpose向外暴露你想獲取的值才行。
5. provide/inject
provide/inject是 Vue 中提供的一對 API。無論層級多深,API 都可以實現(xiàn)父組件到子孫組件的數(shù)據(jù)傳遞。
// 父組件中 provide('list', list.value) // 子組件中 const list = inject('list')
6. eventBus
Vue 3 中移除了 eventBus,但可以借助第三方工具來完成。Vue 官方推薦使用 mitt 或 tiny-emitter。
7. vuex/pinia
Vuex 和 Pinia 是 Vue 3 中的狀態(tài)管理工具,使用這兩個工具可以輕松實現(xiàn)組件通信。
到此這篇關于vue3組件通信方式的文章就介紹到這了,更多相關vue3組件通信內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vuex中...mapstate和...mapgetters的區(qū)別及說明
這篇文章主要介紹了vuex中...mapstate和...mapgetters的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08Ant?Design?of?Vue的樹形控件Tree的使用及說明
這篇文章主要介紹了Ant?Design?of?Vue的樹形控件Tree的使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10Vue中通過Vue.extend動態(tài)創(chuàng)建實例的方法
這篇文章主要介紹了Vue中通過Vue.extend動態(tài)創(chuàng)建實例的方法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08