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

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

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

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

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

1. 父子組件通信:

1.1 Props 傳遞數據:

父組件通過 props 向子組件傳遞數據:WCg28資訊網——每日最新資訊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 觸發事件,父組件通過監聽這些事件來響應:WCg28資訊網——每日最新資訊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 允許你定義哪些內容應該被暴露給父組件,以供父組件訪問。WCg28資訊網——每日最新資訊28at.com

下面是一個簡單的例子,演示如何在子組件中使用 defineExpose 暴露方法:WCg28資訊網——每日最新資訊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 函數進行了暴露。父組件可以通過子組件的引用來調用這個方法。WCg28資訊網——每日最新資訊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 引用子組件,然后可以調用子組件中暴露的方法。WCg28資訊網——每日最新資訊28at.com

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

$listeners批量綁定子組件事件

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

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

以下是一個簡單的例子,演示了 $listeners 的使用:WCg28資訊網——每日最新資訊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 將其傳遞到子組件的相應元素上:WCg28資訊網——每日最新資訊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 事件:WCg28資訊網——每日最新資訊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" 將所有父組件傳遞的事件監聽器應用到了按鈕上,這樣子組件就能夠觸發相應的事件并將數據傳遞給父組件。WCg28資訊網——每日最新資訊28at.com

2. 兄弟組件通信:

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

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

2.2 使用事件總線(Bus):

創建一個事件總線,兄弟組件通過事件總線來通信。在 Vue 3 中,可以使用 provide/inject 來創建一個簡單的事件總線。WCg28資訊網——每日最新資訊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 獲取數據。WCg28資訊網——每日最新資訊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 來實現通信。WCg28資訊網——每日最新資訊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 的狀態管理庫。WCg28資訊網——每日最新資訊28at.com

5. Pinia:

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

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

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

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

npm install pinia

使用 Pinia:WCg28資訊網——每日最新資訊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 更為輕量。WCg28資訊網——每日最新資訊28at.com

下面是 mitt 的基本用法:WCg28資訊網——每日最新資訊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 是一個事件總線實例,可以用于在不同部分之間發送和接收事件。WCg28資訊網——每日最新資訊28at.com

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

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

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

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

標簽:
  • 熱門焦點
  • 六大權益!華為8月服務日開啟:手機免費貼膜、維修免人工費

    8月5日消息,一年一度的華為開發者大會2023(Together)日前在松山湖拉開帷幕,與此同時,華為8月服務日也式開啟,到店可享六大專屬權益。華為用戶可在華為商城Ap
  • CSS單標簽實現轉轉logo

    轉轉品牌升級后更新了全新的Logo,今天我們用純CSS來實現轉轉的新Logo,為了有一定的挑戰性,這里我們只使用一個標簽實現,將最大化的使用CSS能力完成Logo的繪制與動畫效果。新logo
  • 量化指標是與非:挽救被量化指標扼殺的技術團隊

    作者 | 劉新翠整理 | 徐杰承本文整理自快狗打車技術總監劉新翠在WOT2023大會上的主題分享,更多精彩內容及現場PPT,請關注51CTO技術棧公眾號,發消息【WOT2023PPT】即可直接領取
  • 重估百度丨“晚熟”的百度云,能等到春天嗎?

    &copy;自象限原創作者|程心排版|王喻可2016年7月13日,百度云計算戰略發布會在北京舉行,宣告著百度智能云的正式啟程。彼時的會場座無虛席,甚至排隊排到了門外,在場的所有人幾乎都
  • 共享單車的故事講到哪了?

    來源丨海克財經與共享充電寶相差不多,共享單車已很久沒有被國內熱點新聞關照到了。除了一再漲價和用戶直呼用不起了。近日多家媒體再發報道稱,成都、天津、鄭州等地多個共享單
  • 大廠卷向扁平化

    來源:新熵作者丨南枝 編輯丨月見大廠職級不香了。俗話說,兵無常勢,水無常形,互聯網企業調整職級體系并不稀奇。7月13日,淘寶天貓集團啟動了近年來最大的人力制度改革,目前已形成一
  • 當家的盒馬,加速謀生

    來源 | 價值星球Planet作者 | 歸去來自己&ldquo;當家&rdquo;的盒馬,開始加速謀生了。據盒馬官微消息,盒馬計劃今年開放生鮮供應鏈,將其生鮮商品送往食堂。目前,盒馬在上海已經與
  • iQOO 11S新品發布會

    iQOO將在7月4日19:00舉行新品發布會,推出杭州亞運會電競賽事官方用機iQOO 11S。
  • 2299元起!iQOO Pad開啟預售:性能最強天璣平板

    5月23日,iQOO如期舉行了新品發布會,除了首發安卓最強旗艦處理器的iQOO Neo8系列新機外,還在發布會上推出了旗下首款平板電腦——iQOO Pad,其搭載了天璣
Top 主站蜘蛛池模板: 玉林市| 原阳县| 临泽县| 江门市| 明溪县| 安阳县| 儋州市| 子洲县| 兴隆县| 白银市| 台南市| 迭部县| 平凉市| 长春市| 广河县| 奉新县| 苗栗市| 保康县| 温泉县| 镇平县| 玉门市| 涞水县| 洛宁县| 永福县| 清河县| 建瓯市| 潍坊市| 荆州市| 新干县| 龙游县| 衢州市| 徐汇区| 寿阳县| 达日县| 广安市| 婺源县| 芦溪县| 彭阳县| 松江区| 东明县| 溧水县|