Vue 程式札記 : Props 組件傳遞資料

2024/03/21閱讀時間約 3 分鐘

在 Vue 中,組件是構建應用程式的基本單位,而 props 是組件間傳遞資料的主要方式之一,本文將介紹 Vue 中的 props,並通過實際範例展示如何使用 props 實現組件間的資料傳遞。

什麼是 Props?

Props 是 Vue 組件的一個重要概念,用於從父組件向子組件傳遞資料。它是單向綁定的,這意味著資料只能從父組件流向子組件,子組件無法直接修改接收到的 props 值。

Props 基本使用

假設我們有一個名為 ChildComponent 的子組件,我們希望從父組件中接收一個名為 message 的 prop:

<!-- ChildComponent.vue -->
<template>
<div>{{ message }}</div>
</template>

<script setup>
import { defineProps } from 'vue';

const props = defineProps({
message: String
});
</script>

在父組件中,我們可以這樣傳遞 message prop:

<!-- ParentComponent.vue -->
<template>
<ChildComponent message="Hello, Vue!" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';
</script>

在這個範例中,ChildComponent 通過 props 聲明了它期望接收一個名為 message 的 prop,父組件 ParentComponent 通過將 message 屬性綁定到 ChildComponent 標籤上,將字符串 "Hello, Vue!" 傳遞給子組件。

動態 Props

Vue 還允許將 prop 的值綁定到父組件中的動態資料。這意味著當父組件中的資料發生變化時,這些變化會自動反映到子組件中:

<!-- ParentComponent.vue -->
<template>
<ChildComponent :message="dynamicMessage" />
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const dynamicMessage = ref('Hello, Vue!');
</script>

在這個範例中,我們使用了 v-bind 指令(簡寫為 :)將 message prop 的值綁定到父組件的 dynamicMessage 資料屬性,當 dynamicMessage 的值發生變化時,這個變化將自動傳遞給 ChildComponent


😊 感謝你的耐心閱讀,若是你喜歡這篇內容,可以透過以下方式表達你的喜歡 😊

❤️按個愛心|💬留言互動|🔗分享此文|📌追蹤阿梧|☕請喝咖啡

51會員
81內容數
「梧笙」即「吾生」,意即我的生命,朋友都叫我「阿梧(Awu)」,高雄人。我喜歡學習新技能,從程式設計到網路工具,再到社群經營和影片剪輯。日常興趣是打遊戲、看動漫、讀小說和聽音樂。我會把這些興趣寫成文章,如果你有任何想法或問題,歡迎來信到我的郵箱 [email protected]
留言0
查看全部
發表第一個留言支持創作者!