最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

一次搞清Vue3中組件通訊的全部方式

 更新時(shí)間:2024年09月26日 08:57:11   作者:魚(yú)櫻前端  
毫無(wú)疑問(wèn),組件通訊是Vue中非常重要的技術(shù)之一,它的出現(xiàn)能夠使我們非常方便的在不同組件之間進(jìn)行數(shù)據(jù)的傳遞,以達(dá)到數(shù)據(jù)交互的效果,所以,學(xué)習(xí)組件通訊技術(shù)是非常有必要的,本文將一次解決Vue3中組件通訊的全部方式,總有你想要的那一種,需要的朋友可以參考下

Vue 3 提供了多種組件間通信的方法,每種方法適用于不同的場(chǎng)景

1. 父組件向子組件傳遞數(shù)據(jù) (Props)

父組件可以通過(guò) 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)聽(tīng)這些事件來(lái)接收數(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. 兄弟組件通信 (通過(guò)共同父組件或Vuex)

如果組件沒(méi)有直接的父子關(guān)系,可以通過(guò)共同的父組件作為中介或者使用 Vuex 進(jìn)行狀態(tài)管理。

示例 (通過(guò)共同父組件):

// 父組件
<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 可以用來(lái)跨越多個(gè)組件層級(jí)進(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

對(duì)于更復(fù)雜的應(yīng)用程序,通常會(huì)使用 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>計(jì)數(shù)器: {{ counter }}</p>
    <button @click="increment">增加</button>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useStore } from 'vuex';

const store = useStore();

// 使用計(jì)算屬性獲取狀態(tài)
const counter = computed(() => store.state.counter);

// 定義方法以提交mutation
const increment = () => {
  store.commit('increment');
};
</script>

6. 使用事件總線 (Event Bus)

雖然官方文檔不推薦這種方式,但在某些情況下,創(chuàng)建一個(gè)事件總線可以幫助非父子組件間通信。

示例:

import { createApp } from 'vue';

const eventBus = createApp({}).config.globalProperties.$bus;

eventBus.$on('some-event', (data) => {
  // 處理事件
});

7. 使用 Refs

在 Vue 3 中,你可以使用 ref 屬性來(lái)訪問(wèn)子組件實(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 是一個(gè)輕量級(jí)的事件總線庫(kù),可以在 Vue 3 應(yīng)用中用于實(shí)現(xiàn)組件間的通信。

# 使用 pnpm 推薦
pnpm add mitt
# 使用 npm
npm install mitt
# 使用 yarn
yarn add mitt

初始化 mitt

接下來(lái),在項(xiàng)目的某個(gè)共享位置初始化 mitt 實(shí)例。通常,你可以將它放在一個(gè)單獨(dú)的文件中,比如 src/utils/eventBus.js

// src/utils/eventBus.js
import mitt from 'mitt'

// 創(chuàng)建一個(gè)事件總線實(shí)例
const emitter = mitt()

export default emitter

使用 mitt 在組件之間發(fā)送事件

現(xiàn)在,你可以在任何需要的地方導(dǎo)入并使用這個(gè)事件總線實(shí)例。下面是一個(gè)簡(jiǎn)單的例子,展示如何在一個(gè)組件中發(fā)送事件,并在另一個(gè)組件中監(jiān)聽(tīng)事件:

發(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)聽(tīng)事件的組件 (ReceiverComponent.vue)

<template>
  <div>{{ lastMessage }}</div>
</template>

<script setup>
import eventBus from '@/utils/eventBus'

const lastMessage = ref('')

// 監(jiān)聽(tīng)事件
eventBus.on('messageSent', (message) => {
  lastMessage.value = message
})

// 清理函數(shù),確保卸載時(shí)移除事件監(jiān)聽(tīng)器
onBeforeUnmount(() => {
  eventBus.off('messageSent')
})
</script>

9. 使用 pinia

Pinia 是一個(gè)非常強(qiáng)大的狀態(tài)管理庫(kù),類似于 Vuex,但更加簡(jiǎn)潔和靈活。通過(guò) Pinia,我們可以輕松地實(shí)現(xiàn)組件間的通信。Pinia 的狀態(tài)管理機(jī)制使得數(shù)據(jù)的存儲(chǔ)和更新變得非常簡(jiǎn)單,同時(shí)提供了很好的靈活性和可維護(hù)性。這種方法非常適合大型應(yīng)用,尤其是當(dāng)組件間的數(shù)據(jù)流比較復(fù)雜時(shí)

安裝 Pinia

首先,你需要安裝 Pinia。如果你還沒(méi)有安裝,可以通過(guò) npm 或 yarn 來(lái)安裝:

# 使用 pnpm 推薦
pnpm add pinia
# 使用 npm
npm install pinia
# 使用 yarn
yarn add pinia

初始化 Pinia

接下來(lái),在項(xiàng)目的某個(gè)共享位置初始化 Pinia 實(shí)例。通常,你可以將它放在一個(gè)單獨(dú)的文件中,比如 src/stores/index.js

// src/stores/index.js
import { defineStore } from 'pinia'

// 定義一個(gè) 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)聽(tīng)事件的組件 (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,可以通過(guò)封裝一些通用邏輯來(lái)簡(jiǎn)化組件間的通信。

示例:

// 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)目需求和個(gè)人愛(ài)好來(lái),一般都是會(huì)按照pinia 或者 vuex之類的即可解決項(xiàng)目組件間的通訊問(wèn)題了結(jié)合props、provide/inject以及自定義hooks等足夠用了。

到此這篇關(guān)于一次搞清Vue3中組件通訊的全部方式的文章就介紹到這了,更多相關(guān)Vue3組件通訊方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Vue生命周期實(shí)例分析總結(jié)

    Vue生命周期實(shí)例分析總結(jié)

    Vue的生命周期就是vue實(shí)例從創(chuàng)建到銷毀的全過(guò)程,也就是new Vue()開(kāi)始就是vue生命周期的開(kāi)始。Vue實(shí)例有?個(gè)完整的?命周期,也就是從開(kāi)始創(chuàng)建、初始化數(shù)據(jù)、編譯模版、掛載Dom->渲染、更新->渲染、卸載等?系列過(guò)程,稱這是Vue的?命周期
    2022-10-10
  • Vue打包程序部署到Nginx 點(diǎn)擊跳轉(zhuǎn)404問(wèn)題

    Vue打包程序部署到Nginx 點(diǎn)擊跳轉(zhuǎn)404問(wèn)題

    這篇文章主要介紹了Vue打包程序部署到Nginx 點(diǎn)擊跳轉(zhuǎn)404問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • Vue 中 reactive創(chuàng)建對(duì)象類型響應(yīng)式數(shù)據(jù)的方法

    Vue 中 reactive創(chuàng)建對(duì)象類型響應(yīng)式數(shù)據(jù)的方法

    在 Vue 的開(kāi)發(fā)世界里,響應(yīng)式數(shù)據(jù)是構(gòu)建交互性良好應(yīng)用的基礎(chǔ),之前我們了解了ref用于定義基本類型的數(shù)據(jù),今天就來(lái)深入探討一下如何使用reactive定義對(duì)象類型的響應(yīng)式數(shù)據(jù),感興趣的朋友一起看看吧
    2025-02-02
  • vue動(dòng)態(tài)添加路由addRoutes之不能將動(dòng)態(tài)路由存入緩存的解決

    vue動(dòng)態(tài)添加路由addRoutes之不能將動(dòng)態(tài)路由存入緩存的解決

    這篇文章主要介紹了vue動(dòng)態(tài)添加路由addRoutes之不能將動(dòng)態(tài)路由存入緩存的解決方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-02-02
  • Vue.js如何實(shí)現(xiàn)路由懶加載淺析

    Vue.js如何實(shí)現(xiàn)路由懶加載淺析

    Vue是可以自定義指令的,最近學(xué)習(xí)過(guò)程中遇見(jiàn)了一個(gè)需要懶加載的功能,發(fā)現(xiàn)網(wǎng)上這方面的資料較少,所以下面這篇文章主要給大家介紹了關(guān)于Vue.js如何實(shí)現(xiàn)路由懶加載的相關(guān)資料,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-08-08
  • ElementPlus el-message-box樣式錯(cuò)位問(wèn)題及解決

    ElementPlus el-message-box樣式錯(cuò)位問(wèn)題及解決

    這篇文章主要介紹了ElementPlus el-message-box樣式錯(cuò)位問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • vue使用jsMind思維導(dǎo)圖的實(shí)戰(zhàn)指南

    vue使用jsMind思維導(dǎo)圖的實(shí)戰(zhàn)指南

    jsMind是一個(gè)顯示/編輯思維導(dǎo)圖的純javascript類庫(kù),其基于 html5的canvas進(jìn)行設(shè)計(jì),這篇文章主要給大家介紹了關(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的操作方法

    這篇文章主要介紹了vue2老項(xiàng)目中node-sass更換dart-sass的操作方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2024-07-07
  • Vuex 使用 v-model 配合 state的方法

    Vuex 使用 v-model 配合 state的方法

    這篇文章主要介紹了Vuex 使用 v-model 配合 state的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-11-11
  • 淺析Vue3中Excel下載模板并導(dǎo)入數(shù)據(jù)功能的實(shí)現(xiàn)

    淺析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

最新評(píng)論

靖安县| 奉节县| 易门县| 永城市| 石渠县| 瓮安县| 吉隆县| 万年县| 安顺市| 抚顺市| 江城| 彭阳县| 绥宁县| 法库县| 乐陵市| 吴江市| 黑龙江省| 罗城| 成都市| 剑河县| 莱阳市| 绍兴市| 陆川县| 浦城县| 建德市| 台北市| SHOW| 泸州市| 靖安县| 大埔区| 玛纳斯县| 宝坻区| 遵义市| 霍州市| 旺苍县| 延吉市| 会宁县| 崇阳县| 顺平县| 巴楚县| 沁源县|