日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

Vue3.js組件通信,兄弟組件、父子、祖孫組件間通信

來源: 責編: 時間:2024-01-09 08:51:51 232觀看
導讀在 Vue.js 3 中,組件通信主要包括父子組件通信、兄弟組件通信以及祖孫組件通信。以下是各種情況下的常見通信方式:1. 父子組件通信:1.1 Props 傳遞數據:父組件通過 props 向子組件傳遞數據:<!-- Parent.vue --><template>

在 Vue.js 3 中,組件通信主要包括父子組件通信、兄弟組件通信以及祖孫組件通信。以下是各種情況下的常見通信方式:cvu28資訊網——每日最新資訊28at.com

1. 父子組件通信:

1.1 Props 傳遞數據:

父組件通過 props 向子組件傳遞數據:cvu28資訊網——每日最新資訊28at.com

<!-- Parent.vue --><template>  <Child :message="parentMessage" /></template><script>import Child from './Child.vue';export default {  data() {    return {      parentMessage: 'Hello from Parent!'    };  },  components: {    Child  }};</script><!-- Child.vue --><template>  <div>{{ message }}</div></template><script>export default {  props: ['message']};</script>

1.2 事件監聽子組件:

子組件通過 $emit 觸發事件,父組件通過監聽這些事件來響應:cvu28資訊網——每日最新資訊28at.com

<!-- Parent.vue --><template>  <Child @notifyParent="handleNotify" /></template><script>import Child from './Child.vue';export default {  methods: {    handleNotify(message) {      console.log(message); // 處理從子組件傳遞的數據    }  },  components: {    Child  }};</script><!-- Child.vue --><template>  <button @click="notifyParent">Notify Parent</button></template><script>export default {  methods: {    notifyParent() {      this.$emit('notifyParent', 'Hello from Child!');    }  }};</script>

1.3 definEexpose暴露子組件方法

在 Vue 3 中,使用 TypeScript 編寫組件時,如果想要將子組件的方法暴露給父組件,可以使用 defineExpose 函數。defineExpose 允許你定義哪些內容應該被暴露給父組件,以供父組件訪問。cvu28資訊網——每日最新資訊28at.com

下面是一個簡單的例子,演示如何在子組件中使用 defineExpose 暴露方法:cvu28資訊網——每日最新資訊28at.com

// ChildComponent.vue<template>  <div>    <button @click="incrementCounter">Increment Counter</button>  </div></template><script setup>import { ref, defineExpose } from 'vue';const counter = ref(0);const incrementCounter = () => {  counter.value++;};// 暴露方法給父組件defineExpose({  incrementCounter});</script>

在這個例子中,incrementCounter 方法被定義在子組件中,并通過 defineExpose 函數進行了暴露。父組件可以通過子組件的引用來調用這個方法。cvu28資訊網——每日最新資訊28at.com

// ParentComponent.vue<template>  <div>    <ChildComponent ref="childRef" />    <button @click="callChildMethod">Call Child Method</button>  </div></template><script setup>import { ref } from 'vue';const childRef = ref();const callChildMethod = () => {  // 調用子組件的方法  childRef.value.incrementCounter();};</script>

在父組件中,通過 ref 引用子組件,然后可以調用子組件中暴露的方法。cvu28資訊網——每日最新資訊28at.com

這樣,通過 defineExpose 可以在 Vue 3 中很方便地實現子組件方法的暴露。這對于構建可重用組件庫或復雜組件通信場景非常有用。cvu28資訊網——每日最新資訊28at.com

$listeners批量綁定子組件事件

$listeners 是一個對象,包含了父組件傳遞給子組件的所有事件監聽器。這個對象允許子組件將所有未被自身處理的事件監聽器綁定到合適的 HTML 元素上。cvu28資訊網——每日最新資訊28at.com

通常情況下,當你在子組件中使用 v-on="$listeners" 時,它會將所有的父組件傳遞下來的事件監聽器應用到相應的 DOM 元素上。cvu28資訊網——每日最新資訊28at.com

以下是一個簡單的例子,演示了 $listeners 的使用:cvu28資訊網——每日最新資訊28at.com

<!-- ParentComponent.vue --><template>  <ChildComponent @custom-event="handleCustomEvent" /></template><script>import ChildComponent from './ChildComponent.vue';export default {  methods: {    handleCustomEvent(data) {      console.log('Custom Event Handled in Parent:', data);    }  },  components: {    ChildComponent  }};</script>
<!-- ChildComponent.vue --><template>  <div>    <button @click="triggerCustomEvent">Trigger Custom Event</button>  </div></template><script>export default {  methods: {    triggerCustomEvent() {      // 觸發自定義事件并傳遞數據      this.$emit('custom-event', 'Hello from Child');    }  }};</script>

在子組件中,當用戶點擊按鈕時,觸發了一個自定義事件,并通過 $emit 傳遞了數據給父組件。如果你希望在父組件中使用該事件監聽器,可以通過 $listeners 將其傳遞到子組件的相應元素上:cvu28資訊網——每日最新資訊28at.com

<!-- ChildComponent.vue --><template>  <div>    <button @click="triggerCustomEvent" v-on="$listeners">Trigger Custom Event</button>  </div></template><script>export default {  methods: {    triggerCustomEvent() {      // 觸發自定義事件并傳遞數據      this.$emit('custom-event', 'Hello from Child');    }  }};</script>

現在,在父組件中,你可以監聽子組件觸發的 custom-event 事件:cvu28資訊網——每日最新資訊28at.com

<!-- ParentComponent.vue --><template>  <ChildComponent @custom-event="handleCustomEvent" /></template><script>import ChildComponent from './ChildComponent.vue';export default {  methods: {    handleCustomEvent(data) {      console.log('Custom Event Handled in Parent:', data);    }  },  components: {    ChildComponent  }};</script>

在這個例子中,v-on="$listeners" 將所有父組件傳遞的事件監聽器應用到了按鈕上,這樣子組件就能夠觸發相應的事件并將數據傳遞給父組件。cvu28資訊網——每日最新資訊28at.com

2. 兄弟組件通信:

2.1 通過共享狀態(使用父組件):

通過將狀態提升到共同的父組件,然后通過 props 和事件來實現兄弟組件之間的通信。cvu28資訊網——每日最新資訊28at.com

2.2 使用事件總線(Bus):

創建一個事件總線,兄弟組件通過事件總線來通信。在 Vue 3 中,可以使用 provide/inject 來創建一個簡單的事件總線。cvu28資訊網——每日最新資訊28at.com

// EventBus.jsimport { createApp, ref } from 'vue';const bus = createApp();bus.provide('eventBus', bus);// ComponentA.vue<script>export default {  methods: {    notifySibling() {      this.$root.eventBus.emit('siblingEvent', 'Hello from Component A!');    }  }};</script>// ComponentB.vue<script>export default {  created() {    this.$root.eventBus.on('siblingEvent', message => {      console.log(message); // 處理從兄弟組件傳遞的數據    });  }};</script>

3. 祖孫組件通信:

3.1 通過 provide/inject:

使用 provide/inject 可以實現祖孫組件之間的通信,祖先組件通過 provide 提供數據,孫子組件通過 inject 獲取數據。cvu28資訊網——每日最新資訊28at.com

<!-- Grandparent.vue --><template>  <Parent /></template><script>import { ref } from 'vue';import Parent from './Parent.vue';export default {  setup() {    const grandparentMessage = ref('Hello from Grandparent!');    provide('grandparentMessage', grandparentMessage);    return {      grandparentMessage    };  },  components: {    Parent  }};</script><!-- Parent.vue --><template>  <Child /></template><script>import Child from './Child.vue';export default {  components: {    Child  }};</script><!-- Child.vue --><template>  <div>{{ grandparentMessage }}</div></template><script>import { inject } from 'vue';export default {  setup() {    const grandparentMessage = inject('grandparentMessage');    return {      grandparentMessage    };  }};</script>

4. Vuex(全局狀態管理):

如果你的應用中需要管理全局狀態,Vuex 是一個強大的狀態管理庫。通過將狀態存儲在 Vuex 中,不同組件可以通過 Vuex 的 store 來實現通信。cvu28資訊網——每日最新資訊28at.com

// store.jsimport { createStore } from 'vuex';export default createStore({  state: {    message: 'Hello from Vuex!'  },  mutations: {    updateMessage(state, newMessage) {      state.message = newMessage;    }  },  actions: {    changeMessage({ commit }, newMessage) {      commit('updateMessage', newMessage);    }  }});// ComponentA.vue<script>export default {  computed: {    message() {      return this.$store.state.message;    }  },  methods: {    changeMessage() {      this.$store.dispatch('changeMessage', 'New Message');    }  }};</script>// ComponentB.vue<script>export default {  computed: {    message() {      return this.$store.state.message;    }  }};</script>

在 Vue.js 生態系統中,除了 $listeners 之外,還有一些其他狀態管理庫,其中包括 Pinia 和 Tini。這兩個庫提供了不同的方式來處理狀態管理,和 Vuex 一樣,它們都是 Vue 3 的狀態管理庫。cvu28資訊網——每日最新資訊28at.com

5. Pinia:

Pinia 是一個由 Vue.js 團隊開發的狀態管理庫,旨在提供簡單、靈活且性能出色的狀態管理方案。與 Vuex 不同,Pinia 使用了更現代的 API,并且是基于 Composition API 構建的。cvu28資訊網——每日最新資訊28at.com

Pinia 的特點:cvu28資訊網——每日最新資訊28at.com

  • 使用 Composition API 構建。
  • 具有 TypeScript 支持。
  • 基于 Vue 3 的響應式系統。
  • 使用插件系統輕松擴展功能。

安裝 Pinia:cvu28資訊網——每日最新資訊28at.com

npm install pinia

使用 Pinia:cvu28資訊網——每日最新資訊28at.com

import { createPinia } from 'pinia';const pinia = createPinia();export const useStore = pinia.createStore({  state: () => ({ count: 0 }),  actions: {    increment() {      this.state.count++;    }  }});

6.mitt

mitt 是一個簡單而小巧的事件總線庫,用于在應用程序的不同部分之間進行事件通信。它提供了一種簡單的方式來發射和監聽事件。與 Vuex 的 $emit 和 $on 類似,但 mitt 更為輕量。cvu28資訊網——每日最新資訊28at.com

下面是 mitt 的基本用法:cvu28資訊網——每日最新資訊28at.com

import mitt from 'mitt';// 創建事件總線const emitter = mitt();// 監聽事件emitter.on('custom-event', (data) => {  console.log('Event Received:', data);});// 發射事件emitter.emit('custom-event', 'Hello from Mitt!');

在上面的代碼中,emitter 是一個事件總線實例,可以用于在不同部分之間發送和接收事件。cvu28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-58936-0.htmlVue3.js組件通信,兄弟組件、父子、祖孫組件間通信

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 分享12個面向前端開發人員的設計工具,提高你的生產力

下一篇: 深入理解與應用多線程技術

標簽:
  • 熱門焦點
  • 俄羅斯:將審查iPhone等外國公司設備 保數據安全

    iPhone和特斯拉都屬于在各自領域領頭羊的品牌,推出的產品也也都是數一數二的,但對于一些國家而言,它們的產品可靠性和安全性還是在限制范圍內。近日,俄羅斯聯邦通信、信息技術
  • 5月iOS設備好評榜:iPhone 14僅排第43?

    來到新的一月,安兔兔的各個榜單又重新匯總了數據,像安卓陣營的榜單都有著比較大的變動,不過iOS由于設備的更新換代并沒有那么快,所以相對來說變化并不大,特別是iOS好評榜,老款設
  • 線程通訊的三種方法!通俗易懂

    線程通信是指多個線程之間通過某種機制進行協調和交互,例如,線程等待和通知機制就是線程通訊的主要手段之一。 在 Java 中,線程等待和通知的實現手段有以下幾種方式:Object 類下
  • Flowable工作流引擎的科普與實踐

    一.引言當我們在日常工作和業務中需要進行各種審批流程時,可能會面臨一系列技術和業務上的挑戰。手動處理這些審批流程可能會導致開發成本的增加以及業務復雜度的上升。在這
  • 在線圖片編輯器,支持PSD解析、AI摳圖等

    自從我上次分享一個人開發仿造稿定設計的圖片編輯器到現在,不知不覺已過去一年時間了,期間我經歷了裁員失業、面試找工作碰壁,寒冬下一直沒有很好地履行計劃.....這些就放在日
  • 本地生活這塊肥肉,拼多多也想吃一口

    出品/壹覽商業 作者/李彥編輯/木魚拼多多也看上本地生活這塊蛋糕了。近期,拼多多在App首頁&ldquo;充值中心&rdquo;入口上線了本機生活界面。壹覽商業發現,該界面目前主要
  • 馮提莫簽約抖音公會 前“斗魚一姐”消失在直播間

    來源:直播觀察提起&ldquo;馮提莫&rdquo;這個名字,很多網友或許聽過,但應該不記得她是哪位主播了。其實,作為曾經的&ldquo;斗魚一姐&rdquo;,馮提莫在游戲直播的年代影響力不輸于現
  • OPPO K11搭載高性能石墨散熱系統:旗艦同款 性能涼爽釋放

    日前OPPO官方宣布,將于7月25日14:30舉辦新品發布會,屆時全新的OPPO K11將正式與大家見面,將主打旗艦影像,和同檔位競品相比,其最大的賣點就是將配備索尼
  • 親歷馬斯克血洗Twitter,硅谷的苦日子在后頭

    文/劉哲銘  編輯/李薇  馬斯克再次揮下裁員大刀?! ∶绹鴷r間11月14日,Twitter約4400名外包員工遭解雇,此次被解雇的員工的主要工作為內容審核等。此前,T
Top 主站蜘蛛池模板: 双城市| 托克托县| 通化县| 淮北市| 什邡市| 怀柔区| 安吉县| 衡阳市| 桑植县| 石狮市| 怀安县| 精河县| 宝兴县| 崇义县| 关岭| 十堰市| 定襄县| 衡阳县| 阳东县| 凤山市| 武冈市| 筠连县| 寻乌县| 贵定县| 高清| 青田县| 西峡县| 仁化县| 浙江省| 尤溪县| 天长市| 武安市| 汾西县| 正安县| 龙川县| 监利县| 扶风县| 盈江县| 封开县| 建水县| 杭州市|