91
Vue 3 學習之旅
TypeScript 整合
Day 91: defineComponent 的使用
·6 分鐘閱讀·TypeScript 整合
摘要
defineComponent
是一個輔助函數,主要用於在不使用 <script setup> 的情況下(例如在 .js 或 .ts 檔案中定義元件),為 Vue 元件的選項物件提供完整的類型推斷。
定義與說明
當你使用標準的選項式 API 或 setup() 函數時,將元件的選項物件包裹在 defineComponent() 中,TypeScript 就能正確地推斷出 this 的類型,以及 props、data、computed 等選項的內部類型。
實作範例
defineComponent 使用示例
import { defineComponent, ref } from 'vue';
// 使用 defineComponent 包裹選項物件
export default defineComponent({
props: {
name: String
},
setup(props) {
// TS 能正確推斷出 props.name 是 string | undefined
const count = ref(0);
return { count };
},
// TS 能正確推斷出 this 的類型
mounted() {
console.log(this.name, this.count);
}
});
結論
在 <script setup> 成為主流的今天,defineComponent 的使用場景已大幅減少。但如果你在維護舊專案或編寫純 .ts 元件,它依然是獲得良好類型支援的關鍵。
defineComponent 類型推斷 選項式 API