2024-05-12|閱讀時間 ‧ 約 24 分鐘

父子組件資料傳遞 props、emit

    當 父組件 有數據想傳送到 子組件 就可以使用props

    1​. 父層傳遞設置

    可以在父組件的屬性給予一個值,當作要傳送到子組件的資料。

    <!-- App.vue (父組件) -->
    <template>
    <div>
    <ChildComponent greeting="Hello" name="MAY" />
    </div>
    </template>

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

    在 屬性上的props名稱命名規則,須使用kebab-case(烤肉串),不可以使用camelCase(駱峰)。

    2.子層接收數據

    子組件可以宣告props來接收來自父組件的數據,指定數據名稱必須要使用 camelCase (駱峰)來設置接收。

    可以通過在子組件中使用 defineProps 來接收父組件傳遞的 props。

    <!-- ChildComponent.vue (子組件) -->
    <template>
    <div>
    <p>{{ greeting }}, {{ name }}!</p>
    </div>
    </template>

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

    const props = defineProps({
    greeting: String,
    name: String
    });
    </script>

    它被包含在父組件 App.vue 中。它接收來自父組件的 greetingname 兩個 props,並在模板中使用它們。


    那如果今天當你需要在子組件中觸發一個事件並將數據傳遞給父組件時,你可以使用 emit

    <!-- ChildComponent.vue (子組件) -->
    <template>
    <button @click="handleClick">Click me!</button>
    </template>

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

    const emits = defineEmits(['button-click']);

    const handleClick = () => { emits('button-click', 'Some data from child'); }

    </script>

    在子組件中有點擊事件會觸發 handleClick 方法。在這個方法中,我們使用 emits 來觸發一個名為 button-click 的事件,同時將一些數據 'Some data from child' 作為參數傳遞。

    <!-- App.vue (父組件) -->
    <template>
    <div>
    <ChildComponent @button-click="handleButtonClick" />
    <p>{{ message }}</p>
    </div>
    </template>

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

    const message = ref('');

    const handleButtonClick = (data) => { message.value = data; }

    </script>

    在父組件 App.vue 中,我們使用 ChildComponent 並監聽子組件觸發的 button-click 事件。當事件被觸發時,handleButtonClick 方法會被調用並接收從子組件傳遞過來的數據。在這個例子中,我們將這個數據賦值給 message 變量,並在模板中渲染出來。這樣子組件就可以通過 emit 將數據傳遞給父組件。

    參考資料 :

    父子組件資料傳遞 props、$emit | Docs99 (docs-99.vercel.app)


    分享至
    成為作者繼續創作的動力吧!
    從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

    郭欣玫的沙龍 的其他內容

    發表回應

    成為會員 後即可發表留言
    © 2024 vocus All rights reserved.