2024-03-21|閱讀時間 ‧ 約 23 分鐘

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

在 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


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

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

分享至
成為作者繼續創作的動力吧!
歡迎來到 Hello Coding ! 程式札記,我會在這裡分享分享各種程式語言的學習心得,以及任何跟 Coding 相關的內容。這裡的內容會盡量簡單、實用,讓任何對程式設計有興趣的人都能從這裡得到收穫。
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言