在 Vue 3 中,defineProps
和 defineEmits
是組合式 API 中用于定義組件的 props 和 事件 的方法,提供了一種更簡潔和明確的方式來管理組件的輸入和輸出。它們屬于 Composition API 的一部分,在 Vue 2 中通常使用 props
和 $emit
來實現。
1.?defineProps
defineProps
用來定義組件的 props,即組件從父組件接收的屬性。它使得在 <script setup>
中使用 props 變得更加簡單和類型安全。
基本用法:
<script setup>
import { defineProps } from 'vue';// 定義 props
const props = defineProps({msg: {type: String,required: true},count: {type: Number,default: 0}
});
</script><template><div><p>{{ props.msg }}</p><p>{{ props.count }}</p></div>
</template>
解釋:
defineProps
?接收一個對象,可以為每個 prop 提供類型、默認值、是否必填等信息。- 在?
<template>
?中直接訪問?props
,無需手動定義?props
。
類型推導:
如果使用 TypeScript,可以通過類型推導讓 props
更加明確和安全:
<script setup lang="ts">
import { defineProps } from 'vue';interface Props {msg: string;count: number;
}const props = defineProps<Props>();
</script>
2.?defineEmits
defineEmits
用于定義組件觸發的 自定義事件。它讓你在 <script setup>
中聲明組件發出的事件,并確保事件名稱的類型安全。
基本用法:
<script setup>
import { defineEmits } from 'vue';// 定義事件
const emit = defineEmits<{(event: 'update', newValue: string): void;
}>();// 觸發事件
const changeValue = () => {emit('update', 'new value');
};
</script><template><button @click="changeValue">Change Value</button>
</template>
解釋:
defineEmits
?接受一個對象或類型,它定義了所有可能觸發的事件及其參數類型。emit
?是一個函數,用于觸發自定義事件,在 Vue 3 中無需手動綁定?$emit
。
多事件支持:
你也可以定義多個事件:
<script setup>
const emit = defineEmits<{(event: 'update', newValue: string): void;(event: 'delete', id: number): void;
}>();
</script>
3.?組合使用
你可以在一個組件中同時使用 defineProps
和 defineEmits
,以便管理組件的輸入和輸出。
<script setup>
import { defineProps, defineEmits } from 'vue';// 定義 props
const props = defineProps({title: String
});// 定義事件
const emit = defineEmits<{(event: 'updateTitle', newTitle: string): void;
}>();// 觸發事件
const updateTitle = () => {emit('updateTitle', 'New Title');
};
</script><template><h1>{{ props.title }}</h1><button @click="updateTitle">Update Title</button>
</template>
總結:
defineProps
:用于定義組件的輸入(即 props),提供了類型推導和默認值的支持。defineEmits
:用于定義組件的輸出(即觸發的事件),提供了事件類型安全。
這兩個方法大大簡化了組件的編寫,使得代碼更加簡潔、可維護,并且提供了更強的類型安全。如果你用 TypeScript,它們能幫助你避免很多常見的錯誤。