一次搞清Vue3中組件通訊的全部方式
Vue 3 提供了多種組件間通信的方法,每種方法適用于不同的場景
1. 父組件向子組件傳遞數(shù)據(jù) (Props)
父組件可以通過 props 將數(shù)據(jù)傳遞給子組件。
示例:
// 父組件
<template>
<ChildComponent :message="parentMessage" />
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
const parentMessage = 'Hello from Parent';
</script>
// 子組件
<template>
<div>{{ message }}</div>
</template>
<script setup>
defineProps(['message']);
</script>
2. 子組件向父組件傳遞數(shù)據(jù) ($emit)
子組件可以使用 $emit 觸發(fā)事件,父組件監(jiān)聽這些事件來接收數(shù)據(jù)。
示例:
// 父組件
<template>
<ChildComponent @update-message="updateMessage" />
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
function updateMessage(newMessage) {
console.log(newMessage);
}
</script>
// 子組件
<template>
<button @click="sendUpdate">Send Update</button>
</template>
<script setup>
import { defineEmits } from 'vue';
const emit = defineEmits(['update-message']);
function sendUpdate() {
emit('update-message', 'Hello from Child');
}
</script>
3. 兄弟組件通信 (通過共同父組件或Vuex)
如果組件沒有直接的父子關(guān)系,可以通過共同的父組件作為中介或者使用 Vuex 進(jìn)行狀態(tài)管理。
示例 (通過共同父組件):
// 父組件
<template>
<SiblingA @share-data="handleShareData" />
<SiblingB :sharedData="sharedData" />
</template>
<script setup>
import SiblingA from './SiblingA.vue';
import SiblingB from './SiblingB.vue';
const sharedData = ref(null);
function handleShareData(data) {
sharedData.value = data;
}
</script>
4. 使用 provide/inject
provide 和 inject 可以用來跨越多個組件層級進(jìn)行數(shù)據(jù)傳遞。
示例:
// 父組件
<template>
<ChildComponent />
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
provide('parentMessage', 'Hello from Parent');
</script>
// 子組件
<template>
<div>{{ message }}</div>
</template>
<script setup>
import { inject } from 'vue';
const message = inject('parentMessage');
</script>
5. 使用 Vuex 或 Pinia
對于更復(fù)雜的應(yīng)用程序,通常會使用 Vuex 或 Pinia 進(jìn)行狀態(tài)管理。
示例 (Vuex):
// Vuex Store
// store.js
import { createStore } from 'vuex';
export default createStore({
state: {
counter: 0,
},
mutations: {
increment(state) {
state.counter++;
},
},
});
// 組件中使用 Vuex
<template>
<div>
<p>計數(shù)器: {{ counter }}</p>
<button @click="increment">增加</button>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useStore } from 'vuex';
const store = useStore();
// 使用計算屬性獲取狀態(tài)
const counter = computed(() => store.state.counter);
// 定義方法以提交mutation
const increment = () => {
store.commit('increment');
};
</script>
6. 使用事件總線 (Event Bus)
雖然官方文檔不推薦這種方式,但在某些情況下,創(chuàng)建一個事件總線可以幫助非父子組件間通信。
示例:
import { createApp } from 'vue';
const eventBus = createApp({}).config.globalProperties.$bus;
eventBus.$on('some-event', (data) => {
// 處理事件
});
7. 使用 Refs
在 Vue 3 中,你可以使用 ref 屬性來訪問子組件實(shí)例,并調(diào)用其方法或?qū)傩浴?/p>
示例:
// 父組件
<template>
<ChildComponent ref="childRef" />
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const childRef = ref();
function callChildMethod() {
childRef.value.childMethod();
}
</script>
8. 使用 mitt
mitt 是一個輕量級的事件總線庫,可以在 Vue 3 應(yīng)用中用于實(shí)現(xiàn)組件間的通信。
# 使用 pnpm 推薦 pnpm add mitt # 使用 npm npm install mitt # 使用 yarn yarn add mitt
初始化 mitt
接下來,在項(xiàng)目的某個共享位置初始化 mitt 實(shí)例。通常,你可以將它放在一個單獨(dú)的文件中,比如 src/utils/eventBus.js:
// src/utils/eventBus.js import mitt from 'mitt' // 創(chuàng)建一個事件總線實(shí)例 const emitter = mitt() export default emitter
使用 mitt 在組件之間發(fā)送事件
現(xiàn)在,你可以在任何需要的地方導(dǎo)入并使用這個事件總線實(shí)例。下面是一個簡單的例子,展示如何在一個組件中發(fā)送事件,并在另一個組件中監(jiān)聽事件:
發(fā)送事件的組件 (SenderComponent.vue)
<template>
<button @click="sendMessage">Send Message</button>
</template>
<script setup>
import eventBus from '@/utils/eventBus'
function sendMessage() {
eventBus.emit('messageSent', 'Hello from Sender')
}
</script>
監(jiān)聽事件的組件 (ReceiverComponent.vue)
<template>
<div>{{ lastMessage }}</div>
</template>
<script setup>
import eventBus from '@/utils/eventBus'
const lastMessage = ref('')
// 監(jiān)聽事件
eventBus.on('messageSent', (message) => {
lastMessage.value = message
})
// 清理函數(shù),確保卸載時移除事件監(jiān)聽器
onBeforeUnmount(() => {
eventBus.off('messageSent')
})
</script>
9. 使用 pinia
Pinia 是一個非常強(qiáng)大的狀態(tài)管理庫,類似于 Vuex,但更加簡潔和靈活。通過 Pinia,我們可以輕松地實(shí)現(xiàn)組件間的通信。Pinia 的狀態(tài)管理機(jī)制使得數(shù)據(jù)的存儲和更新變得非常簡單,同時提供了很好的靈活性和可維護(hù)性。這種方法非常適合大型應(yīng)用,尤其是當(dāng)組件間的數(shù)據(jù)流比較復(fù)雜時
安裝 Pinia
首先,你需要安裝 Pinia。如果你還沒有安裝,可以通過 npm 或 yarn 來安裝:
# 使用 pnpm 推薦 pnpm add pinia # 使用 npm npm install pinia # 使用 yarn yarn add pinia
初始化 Pinia
接下來,在項(xiàng)目的某個共享位置初始化 Pinia 實(shí)例。通常,你可以將它放在一個單獨(dú)的文件中,比如 src/stores/index.js:
// src/stores/index.js
import { defineStore } from 'pinia'
// 定義一個 store
export const useMainStore = defineStore('main', {
state: () => ({
message: 'Hello from Pinia'
}),
actions: {
updateMessage(newMessage) {
this.message = newMessage
}
}
})
配置 Pinia
在主應(yīng)用文件中配置 Pinia,并將其注入到 Vue 應(yīng)用中:
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import { useMainStore } from './stores/index'
const app = createApp(App)
// 創(chuàng)建 Pinia 實(shí)例
const pinia = createPinia()
// 使用 Pinia
app.use(pinia)
// 掛載應(yīng)用
app.mount('#app')
使用 Pinia 在組件之間發(fā)送事件
發(fā)送事件的組件 (SenderComponent.vue)
<template>
<button @click="sendMessage">Send Message</button>
</template>
<script setup>
import { useMainStore } from '@/stores/index'
const mainStore = useMainStore()
function sendMessage() {
mainStore.updateMessage('Hello from Sender')
}
</script>
監(jiān)聽事件的組件 (ReceiverComponent.vue)
<template>
<div>{{ message }}</div>
</template>
<script setup>
import { useMainStore } from '@/stores/index'
const mainStore = useMainStore()
const message = computed(() => mainStore.message)
</script>
10. 使用自定義 Hook
Vue 3 的 Composition API 支持自定義 Hook,可以通過封裝一些通用邏輯來簡化組件間的通信。
示例:
// src/hooks/useCounter.js
import { ref, onMounted } from 'vue';
export function useCounter(initialValue) {
const count = ref(initialValue);
function increment() {
count.value++;
}
return { count, increment };
}
然后在組件中使用:
<template>
<button @click="increment">{{ count }}</button>
</template>
<script setup>
import { useCounter } from '@/hooks/useCounter';
const { count, increment } = useCounter(0);
</script>
以上的方法都可以在Vue3中得到良好體現(xiàn),具體選擇哪種看自己項(xiàng)目需求和個人愛好來,一般都是會按照pinia 或者 vuex之類的即可解決項(xiàng)目組件間的通訊問題了結(jié)合props、provide/inject以及自定義hooks等足夠用了。
到此這篇關(guān)于一次搞清Vue3中組件通訊的全部方式的文章就介紹到這了,更多相關(guān)Vue3組件通訊方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue打包程序部署到Nginx 點(diǎn)擊跳轉(zhuǎn)404問題
這篇文章主要介紹了Vue打包程序部署到Nginx 點(diǎn)擊跳轉(zhuǎn)404問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
Vue 中 reactive創(chuàng)建對象類型響應(yīng)式數(shù)據(jù)的方法
在 Vue 的開發(fā)世界里,響應(yīng)式數(shù)據(jù)是構(gòu)建交互性良好應(yīng)用的基礎(chǔ),之前我們了解了ref用于定義基本類型的數(shù)據(jù),今天就來深入探討一下如何使用reactive定義對象類型的響應(yīng)式數(shù)據(jù),感興趣的朋友一起看看吧2025-02-02
vue動態(tài)添加路由addRoutes之不能將動態(tài)路由存入緩存的解決
這篇文章主要介紹了vue動態(tài)添加路由addRoutes之不能將動態(tài)路由存入緩存的解決方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
ElementPlus el-message-box樣式錯位問題及解決
這篇文章主要介紹了ElementPlus el-message-box樣式錯位問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
vue使用jsMind思維導(dǎo)圖的實(shí)戰(zhàn)指南
jsMind是一個顯示/編輯思維導(dǎo)圖的純javascript類庫,其基于 html5的canvas進(jìn)行設(shè)計,這篇文章主要給大家介紹了關(guān)于vue使用jsMind思維導(dǎo)圖的相關(guān)資料,需要的朋友可以參考下2023-01-01
vue2老項(xiàng)目中node-sass更換dart-sass的操作方法
這篇文章主要介紹了vue2老項(xiàng)目中node-sass更換dart-sass的操作方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-07-07
淺析Vue3中Excel下載模板并導(dǎo)入數(shù)據(jù)功能的實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了Vue3中的Excel數(shù)據(jù)管理,即下載模板并導(dǎo)入數(shù)據(jù)功能的實(shí)現(xiàn),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考一下2024-05-05

