父組件向子組件傳遞 Ref 變數並反應數值變化 - daniel-qa/Vue GitHub Wiki

父組件向子組件傳遞 Ref 變數並反應數值變化

Vue3 Setup Script:父組件向子組件傳遞 Ref 變數並反應數值變化

在 Vue3 中,使用 Setup Script 語法可以更簡潔地撰寫組件邏輯。若要讓父組件向子組件傳遞 Ref 變數,並使子組件頁面能反應數值變化,可以透過以下幾種方式實現:

Props 傳遞

  • 父組件:
<template>
  <ChildComponent :count="count" />
</template>

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

const count = ref(0);

// 定期更新 count
setInterval(() => {
  count.value++;
}, 1000);
</script>
  • 子組件:
<template>
  <p>Count: {{ count }}</p>
</template>

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

const props = defineProps({
  count: {
    type: Number,
    required: true
  }
});
</script>
  • 說明:

父組件使用 :count="count" 將 Ref 變數 count 傳遞給子組件。

子組件使用 defineProps 接收父組件傳遞的 count 屬性。

子組件可以直接在模板中使用 count,當父組件的 count 變動時,子組件會自動更新。

⚠️ **GitHub.com Fallback** ⚠️