3.2版的 defineProps 和 defineEmits - daniel-qa/Vue GitHub Wiki
這是一個 Vue 3 defineProps 和 defineEmits 範例,演示如何在父子組件之間傳遞數據和事件。
-
父組件,會把 變數和 更新變數的函式,傳給子組件
-
子組件 emit 的事件名稱要與父組件監聽的名稱匹配;區分大小寫
-
變數類型: String,Number,Type,Array
子組件接收 message 屬性,並在按鈕點擊時透過 emit 發送事件給父組件。
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
message: String
});
const emit = defineEmits(['updateMessage']);
const sendMessage = () => {
emit('updateMessage', '子組件發送的新消息!');
};
</script>
<template>
<div>
<p>來自父組件的消息:{{ props.message }}</p>
<button @click="sendMessage">發送消息給父組件</button>
</div>
</template>
父組件傳遞 message 屬性給子組件,並監聽 updateMessage 事件來更新 message。
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const message = ref('Hello from Parent!');
const updateMessage = (newMessage) => {
message.value = newMessage;
};
</script>
<template>
<div>
<h2>父組件</h2>
<p>當前消息:{{ message }}</p>
<ChildComponent :message="message" @updateMessage="updateMessage" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const title = ref('預設標題');
const content = ref('這是一段內容');
const updateTitle = (newTitle) => {
title.value = newTitle;
};
const updateContent = (newContent) => {
content.value = newContent;
};
</script>
<template>
<div>
<h2>父組件</h2>
<p>標題:{{ title }}</p>
<p>內容:{{ content }}</p>
<ChildComponent
:title="title"
:content="content"
@updateTitle="updateTitle"
@updateContent="updateContent"
/>
</div>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
title: String,
content: String
});
const emit = defineEmits(['updateTitle', 'updateContent']);
const updateTitle = () => {
emit('updateTitle', '新標題 from 子組件');
};
const updateContent = () => {
emit('updateContent', '新內容 from 子組件');
};
</script>
<template>
<div>
<h3>子組件</h3>
<p>標題:{{ props.title }}</p>
<p>內容:{{ props.content }}</p>
<button @click="updateTitle">更新標題</button>
<button @click="updateContent">更新內容</button>
</div>