W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
Vue CLI 提供內置的 TypeScript 工具支持。
隨著應用的增長,靜態(tài)類型系統可以幫助防止許多潛在的運行時錯誤,這就是為什么 Vue 3 是用 TypeScript 編寫的。這意味著在 Vue 中使用 TypeScript 不需要任何其他工具——它具有一流的公民支持。
// tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
// 這樣就可以對 `this` 上的數據屬性進行更嚴格的推斷`
"strict": true,
"jsx": "preserve",
"moduleResolution": "node"
}
}
請注意,必須包含 strict: true
(或至少包含 noImplicitThis: true
,它是 strict
標志的一部分) 才能在組件方法中利用 this
的類型檢查,否則它總是被視為 any
類型。
參見 TypeScript 編譯選項文檔查看更多細節(jié)。
Vue CLI 可以生成使用 TypeScript 的新項目,開始:
## 1. Install Vue CLI, 如果尚未安裝
npm install --global @vue/cli@next
## 2. 創(chuàng)建一個新項目, 選擇 "Manually select features" 選項
vue create my-project-name
## 3. 如果已經有一個不存在TypeScript的 Vue CLI項目,請?zhí)砑舆m當的 Vue CLI插件:
vue add typescript
請確保組件的 script
部分已將語言設置為 TypeScript:
<script lang="ts">
...
</script>
對于使用 TypeScript 開發(fā) Vue 應用程序,我們強烈建議使用 Visual Studio Code,它為 TypeScript 提供了很好的開箱即用支持。如果你使用的是單文件組件 (SFCs),那么可以使用很棒的 Vetur extension,它在 SFCs 中提供了 TypeScript 推理和許多其他優(yōu)秀的特性。
WebStorm 還為 TypeScript 和 Vue 提供現成的支持。
要讓 TypeScript 正確推斷 Vue 組件選項中的類型,需要使用 defineComponent
全局方法定義組件:
import { defineComponent } from 'vue'
const Component = defineComponent({
// 已啟用類型推斷
})
TypeScript 應該能夠在不顯式定義類型的情況下推斷大多數類型。例如,如果有一個具有數字 count
property 的組件,如果試圖對其調用特定于字符串的方法,則會出現錯誤:
const Component = defineComponent({
data() {
return {
count: 0
}
},
mounted() {
const result = this.count.split('') // => Property 'split' does not exist on type 'number'
}
})
如果你有一個復雜的類型或接口,你可以使用 type assertion 對其進行強制轉換:
interface Book {
title: string
author: string
year: number
}
const Component = defineComponent({
data() {
return {
book: {
title: 'Vue 3 Guide',
author: 'Vue Team',
year: 2020
} as Book
}
}
})
由于 Vue 聲明文件的循環(huán)特性,TypeScript 可能難以推斷 computed 的類型。因此,你可能需要注釋返回類型的計算屬性。
import { defineComponent } from 'vue'
const Component = defineComponent({
data() {
return {
message: 'Hello!'
}
},
computed: {
// 需要注釋
greeting(): string {
return this.message + '!'
}
// 在使用setter進行計算時,需要對getter進行注釋
greetingUppercased: {
get(): string {
return this.greeting.toUpperCase();
},
set(newValue: string) {
this.message = newValue.toUpperCase();
},
},
}
})
Vue 對定義了 type
的 prop 執(zhí)行運行時驗證。要將這些類型提供給 TypeScript,我們需要使用 PropType
強制轉換構造函數:
import { defineComponent, PropType } from 'vue'
interface ComplexMessage {
title: string
okMessage: string
cancelMessage: string
}
const Component = defineComponent({
props: {
name: String,
success: { type: String },
callback: {
type: Function as PropType<() => void>
},
message: {
type: Object as PropType<ComplexMessage>,
required: true,
validator(message: ComplexMessage) {
return !!message.title
}
}
}
})
如果你發(fā)現驗證器沒有得到類型推斷或者成員完成不起作用,那么用期望的類型注釋參數可能有助于解決這些問題。
在 setup()
函數中,不需要將類型傳遞給 props
參數,因為它將從 props
組件選項推斷類型。
import { defineComponent } from 'vue'
const Component = defineComponent({
props: {
message: {
type: String,
required: true
}
},
setup(props) {
const result = props.message.split('') // 正確, 'message' 被聲明為字符串
const filtered = props.message.filter(p => p.value) // 將引發(fā)錯誤: Property 'filter' does not exist on type 'string'
}
})
ref
Refs 根據初始值推斷類型:
import { defineComponent, ref } from 'vue'
const Component = defineComponent({
setup() {
const year = ref(2020)
const result = year.value.split('') // => Property 'split' does not exist on type 'number'
}
})
有時我們可能需要為 ref 的內部值指定復雜類型。我們可以在調用 ref 重寫默認推理時簡單地傳遞一個泛型參數:
const year = ref<string | number>('2020') // year's type: Ref<string | number>
year.value = 2020 // ok!
TIP
如果泛型的類型未知,建議將 ref
轉換為 Ref<T>
。
reactive
當聲明類型 reactive
property,我們可以使用接口:
import { defineComponent, reactive } from 'vue'
interface Book {
title: string
year?: number
}
export default defineComponent({
name: 'HelloWorld',
setup() {
const book = reactive<Book>({ title: 'Vue 3 Guide' })
// or
const book: Book = reactive({ title: 'Vue 3 Guide' })
// or
const book = reactive({ title: 'Vue 3 Guide' }) as Book
}
})
computed
計算值將根據返回值自動推斷類型
import { defineComponent, ref, computed } from 'vue'
export default defineComponent({
name: 'CounterButton',
setup() {
let count = ref(0)
// 只讀
const doubleCount = computed(() => count.value * 2)
const result = doubleCount.value.split('') // => Property 'split' does not exist on type 'number'
}
})
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯系方式:
更多建議: