深度解析Vue.js組件間的通信方式

Vue.js 組件通信主要通過以下幾種方式來實現:

Props(屬性)

  • 方向:父組件到子組件
  • 用途:父組件通過屬性向子組件傳遞數據。
  • 特性:
    • 只讀:默認情況下,子組件不能改變props的值。
    • 驗證:可以通過props選項定義驗證規則。
    • 動態:props的值可以隨父組件狀態的變化而變化。
父組件(Parent.vue)
<template><div><ChildComponent :message="parentMessage" /></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},data() {return {parentMessage: 'Hello from Parent'};}
};
</script>
子組件(ChildComponent.vue)
<template><div><p>{{ message }}</p></div>
</template><script>
export default {props: {message: String}
};
</script>

$emit(事件)

  • 方向:子組件到父組件
  • 用途:子組件通過觸發自定義事件來通知父組件。
  • 特性:
    • 傳遞數據:事件可以攜帶數據。
    • 多個事件:子組件可以觸發多個不同的事件。
子組件(ChildComponent.vue)
<template><button @click="notifyParent">Notify Parent</button>
</template><script>
export default {methods: {notifyParent() {this.$emit('child-event', 'Hello from Child');}}
};
</script>
父組件(Parent.vue)
<template><ChildComponent @child-event="handleChildEvent" />
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},methods: {handleChildEvent(data) {console.log('Received data from child:', data);}}
};
</script>

Vuex

  • 全局狀態管理
  • 用途:用于管理整個應用的狀態,任何組件都可以訪問。
  • 特性:
    • State:存儲全局狀態。
    • Mutations:唯一改變state的方式,同步操作。
    • Actions:用于異步操作,可以派發mutations。
    • Getters:計算屬性,基于state創建緩存的屬性。
    • Modules:大型應用中可以分割狀態管理模塊。
首先,設置 Vuex Store:

store.js

import Vue from 'vue';
import Vuex from 'vuex';Vue.use(Vuex);export default new Vuex.Store({state: {sharedCounter: 0},mutations: {increment(state) {state.sharedCounter++;}},actions: {incrementAsync({ commit }) {setTimeout(() => {commit('increment');}, 1000);}},getters: {getCounter: state => state.sharedCounter}
});

主應用(main.js)

確保應用使用了 Vuex Store

import Vue from 'vue';
import App from './App.vue';
import store from './store';new Vue({store,render: h => h(App)
}).$mount('#app');
父/子組件使用 Vuex

可以在任何組件中通過 this.$store 訪問 Vuex Store

ComponentUsingVuex.vue

<template><div><p>Counter: {{ counter }}</p><button @click="increment">Increment</button><button @click="incrementAsync">Increment Async</button></div>
</template><script>
export default {computed: {counter() {return this.$store.getters.getCounter;}},methods: {increment() {this.$store.commit('increment');},incrementAsync() {this.$store.dispatch('incrementAsync');}}
};
</script>

Provide/Inject

  • 跨級通信
  • 用途:允許祖先組件提供數據,后代組件注入數據,無需依賴父組件層級。
  • 特性:
    • 不受組件層次限制,但可能導致代碼耦合度增加。
    • 不推薦在常規組件通信中廣泛使用,更適合庫或框架級別的數據傳遞。
祖先組件(AncestorComponent.vue)
<template><div><ChildComponent /></div>
</template><script>
export default {provide() {return {ancestorValue: 'Value from Ancestor'};}
};
</script>
后代組件(DescendantComponent.vue)
<template><div><p>Value from Ancestor: {{ injectedValue }}</p></div>
</template><script>
export default {inject: ['ancestorValue'],mounted() {console.log('Injected value:', this.injectedValue);}
};
</script>

Ref 和 v-model

  • 直接引用
  • 用途:父組件直接引用子組件實例,或雙向數據綁定。
  • 特性:
    • Refs:用于獲取子組件實例或DOM元素,進行直接操作。
    • v-model:用于雙向數據綁定,常見于表單元素,也可以應用于自定義組件。
父組件(ParentComponent.vue)
<template><ChildComponent ref="childRef" v-model="parentValue" /><button @click="logChildRef">Log Child Ref</button>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},data() {return {parentValue: 'Initial Value'};},methods: {logChildRef() {console.log(this.$refs.childRef);}}
};
</script>
子組件(ChildComponent.vue)
<template><input :value="value" @input="$emit('input', $event.target.value)" />
</template><script>
export default {props: ['value']
};
</script>

Custom Events(自定義事件)

  • 事件通信
  • 用途:自定義事件允許組件間非標準的通信。
  • 特性:
    • 可以在任何組件之間觸發和監聽。
    • 適用于特定的交互或組件間的復雜通信。
子組件(ChildComponent.vue)
<template><button @click="customEvent">Send Custom Event</button>
</template><script>
export default {methods: {customEvent() {this.$emit('custom-event', 'Data to send');}}
};
</script>
父組件(ParentComponent.vue)
<template><ChildComponent @custom-event="handleCustomEvent" />
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},methods: {handleCustomEvent(data) {console.log('Received custom event data:', data);}}
};
</script>

Slots(插槽)

  • 內容分發
  • 用途:允許父組件的內容插入到子組件的特定位置。
  • 特性:
    • 默認插槽:子組件的默認內容區域。
    • 具名插槽:子組件可以定義多個插槽,父組件指定插入內容的位置。
    • 作用域插槽:父組件可以訪問子組件的數據來決定插槽內容。
父組件(ParentComponent.vue)
<template><WrapperComponent><h1 slot="header">Custom Header</h1><p slot="body">Custom Body Content</p></WrapperComponent>
</template><script>
import WrapperComponent from './WrapperComponent.vue';export default {components: {WrapperComponent}
};
</script>
WrapperComponent.vue
<template><div><slot name="header"></slot><div class="content"><slot name="body"></slot></div></div>
</template>

Composition API(組合API)

  • 新功能
  • 用途:Vue 3引入的新特性,允許在組件內更好地組織邏輯和數據。
  • 特性:
    • setup() 函數:在組件生命周期開始時運行,可以訪問props和觸發生命周期鉤子。
    • refreactive:用于響應式數據管理。
    • provideinject:在組合API中也有相應的實現,更靈活地進行跨組件數據傳遞。
父組件(ParentComponent.vue)
<template><ChildComponent :count="count" @updateCount="updateCount" />
</template><script>
import { ref, onMounted } from 'vue';
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},setup() {const count = ref(0);function updateCount(newCount) {count.value = newCount;}onMounted(() => {console.log('Initial count:', count.value);});return {count,updateCount};}
};
</script>
子組件(ChildComponent.vue)
<template><button @click="increment">Increment</button>
</template><script>
import { ref, emit } from 'vue';export default {props: ['count'],setup(props) {const count = ref(props.count);function increment() {count.value++;emit('updateCount', count.value);}return {count,increment};}
};
</script>

2500G計算機入門到高級架構師開發資料超級大禮包免費送!

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/17873.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/17873.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/17873.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

關于學習Go語言的并發編程

開始之前&#xff0c;介紹一下?最近很火的開源技術&#xff0c;低代碼。 作為一種軟件開發技術逐漸進入了人們的視角里&#xff0c;它利用自身獨特的優勢占領市場一角——讓使用者可以通過可視化的方式&#xff0c;以更少的編碼&#xff0c;更快速地構建和交付應用軟件&#…

【數據結構】直接選擇排序詳解!

文章目錄 1.直接選擇排序 1.直接選擇排序 &#x1f427; begin 有可能就是 maxi &#xff0c;所以交換的時候&#xff0c;要及時更新 maxi &#x1f34e; 直接選擇排序是不穩定的&#xff0c;例如&#xff1a; 9 [9] 5 [5]&#xff0c;排序后&#xff0c;因為直接選擇排序是會…

Debug-012-el-popover 使用 doClose() 關閉窗口不生效的處理方案

前言&#xff1a; 今天上午碰見一個非常奇怪的情況&#xff1a;一樣的方法實現的功能&#xff0c;效果卻不一樣。 兩個頁面都是使用的doClose()去關閉的el-popover&#xff0c;其中有一個就是不生效&#xff0c;找不同找了半天&#xff0c;始終不得其解。請看效果吧&#xff1…

Day 5:2785. 將字符串中的元音字母排序

Leetcode 2785. 將字符串中的元音字母排序 給你一個下標從 0 開始的字符串 s &#xff0c;將 s 中的元素重新 排列 得到新的字符串 t &#xff0c;它滿足&#xff1a; 所有輔音字母都在原來的位置上。更正式的&#xff0c;如果滿足 0 < i < s.length 的下標 i 處的 s[i] …

【第5章】SpringBoot整合Druid

文章目錄 前言一、啟動器二、配置1.JDBC 配置2.連接池配置3. 監控配置 三、配置多數據源1. 添加配置2. 創建數據源 四、配置 Filter1. 配置Filter2. 可配置的Filter 五、獲取 Druid 的監控數據六、案例1. 問題2. 引入庫3. 配置4. 配置類5. 測試類6. 測試結果 七、案例 ( 推薦 )…

理解磁盤分區與管理:U啟、PE、DiskGenius、MBR與GUID

目錄 U啟和PE的區別: U啟(U盤啟動): PE(預安裝環境)&#xff1a; 在DiskGenius中分區完成之后是否還需要格式化&#xff1a; 1.建立文件系統&#xff1a; 2.清除數據&#xff1a; 3.檢查并修復分區&#xff1a; 分區表格式中&#xff0c;MBR和GUID的區別&#xff1a; 1…

移動端開發 筆記01

目錄 01 移動端的概述 02 移動端的視口標簽 03 開發中的二倍圖 04 流式布局 05 彈性盒子布局 01 移動端的概述 移動端包括:手機 平板 便攜式設備 目前主流的移動端開發: 安卓設備 IOS設備 只要移動端支持瀏覽器 那么就可以使用瀏覽器開發移動端項目 開發移動端 使用…

怎么看外國的短視頻:四川鑫悅里文化傳媒有限公司

怎么看外國的短視頻&#xff1a;跨文化視角下的觀察與思考 隨著全球化進程的加速和網絡技術的飛速發展&#xff0c;外國短視頻逐漸走進了我們的視野。這些來自不同文化背景、語言體系和審美觀念的短視頻作品&#xff0c;為我們打開了一扇了解世界的窗口。然而&#xff0c;如何…

golang中的md5、sha256數據加密文件md5/sha256值計算步驟和運行內存圖解

在go語言中對數據計算一個md5&#xff0c;或sha256和其他語言 如java, php中的使用方式稍有不同&#xff0c; 那就是要加密的數據必須通過流的形式寫入到你創建的Hash對象中。 Hash數據加密步驟 1. 先使用對應的加密算法包中的New函數創建一個Hash對象&#xff0c;(這個也就是…

leetCode. 85. 最大矩形

leetCode. 85. 最大矩形 部分參考上一題鏈接 leetCode.84. 柱狀圖中最大的矩形 此題思路 代碼 class Solution { public:int largestRectangleArea( vector<int>& h ) {int n h.size();vector<int> left( n ), right( n );stack<int> st;// 求每個矩形…

vue/uniapp 企業微信H5使用JS-SDK

企業微信H5需要我們使用一些SDK方法如獲取外部聯系人userid 獲取當前外部聯系人userid 使用SDK前提是如何通過config接口注入權限驗證配置 使用說明 - 接口文檔 - 企業微信開發者中心 當前項目是vue項目&#xff0c;不好直接使用 引入JS文件&#xff0c;但我們可以安裝依賴…

使用nexus搭建的docker私庫,定期清理無用的鏡像,徹底釋放磁盤空間

一、背景 我們使用nexus搭建了docker鏡像&#xff0c;隨著推送的鏡像數量越來越多&#xff0c;導致nexus服務器的磁盤空間不夠用了。于是&#xff0c;我們急需先手動刪除一些過期的鏡像&#xff0c;可發現磁盤空間并沒有釋放。 那么&#xff0c;如何才能徹底釋放掉呢&#xff…

FreeRTOS學習 -- 任務 API 函數

函數 uxTaskPriorityGet() 此函數用來查詢指定任務的優先級&#xff0c;要使用此函數的話宏 INCLUDE_uxTaskPriorityGet 應該定義為 1。 函數 vTaskPrioritySet() 此函數用于改變某一個任務的任務優先級&#xff0c;要 使 用 此 函 數 的 話 宏 INCLUDE_vTaskPrioritySet 應…

一維數組操作(GOC常考類型)答案

第1題 宇航局招聘 時限&#xff1a;1s 空間&#xff1a;256m 宇航局準備招收一批科研人員從事月球探索的航空科研工作。這個職位來了很多應聘者&#xff0c;宇航局對眾多應聘者進行綜合素質考試&#xff0c;最終會選出x名綜合得分排名靠前應聘者。目前考試已經結束了&a…

Golang | Leetcode Golang題解之第102題二叉樹的層序遍歷

題目&#xff1a; 題解&#xff1a; func levelOrder(root *TreeNode) [][]int {ret : [][]int{}if root nil {return ret}q : []*TreeNode{root}for i : 0; len(q) > 0; i {ret append(ret, []int{})p : []*TreeNode{}for j : 0; j < len(q); j {node : q[j]ret[i] …

Java面試精粹:高級問題與解答集錦(一)

Java 面試問題及答案 1. 什么是Java的垃圾回收機制&#xff0c;它如何工作&#xff1f; 答案&#xff1a; Java的垃圾回收機制是一種自動內存管理功能&#xff0c;用于回收不再被應用程序使用的對象所占用的內存。它通過垃圾收集器&#xff08;Garbage Collector&#xff0c;…

js數據類型顯隱式轉換

在JavaScript中&#xff0c;數據類型的轉換可以分為兩種主要類型&#xff1a;顯式類型轉換&#xff08;Explicit Type Conversion&#xff09;和隱式類型轉換&#xff08;Implicit Type Conversion 或 Type Coercion&#xff09;。 顯式類型轉換&#xff08;Explicit Type Con…

React18+TypeScript搭建通用中后臺項目實戰02 整合 antd 和 axios

配置路徑別名 tsconfig.json {"compilerOptions": {"target": "ES2020","useDefineForClassFields": true,"lib": ["ES2020","DOM","DOM.Iterable"],"module": "ESNext&quo…

磁盤分區和掛載

磁盤分區和掛載 一、磁盤 業務層面&#xff1a;滿足一定的需求所是做的特定操作 硬盤是什么以及硬盤的作用 硬盤&#xff1a;計算器的存儲設備&#xff0c;一個或者多個磁性的盤片做成&#xff0c;可以在盤片上進行數據的讀寫 連接方式&#xff1a;內部設備&#xff0c;外…

深度揭秘:藍海創意云渲染農場的五大特色功能

在當今數字化時代&#xff0c;影視制作、效果圖設計等領域對于高質量的渲染需求日益增長。在這個背景下&#xff0c;云渲染平臺成為了行業中不可或缺的一部分&#xff0c;它為用戶提供了高效、靈活的渲染解決方案。藍海創意云渲染農場https://www.vsochina.com/cn/render藍海創…