原文發(fā)于: https://www.yuque.com/xiongzichao/blog/gvk7gt
Vue3.0 one piece版本已于近日發(fā)布,作為Vue鐵粉,來嘗嘗鮮,體驗一下正式版本的各種特性。這里記錄一個小組件從Vue2.x -> Vue3.0的踩坑過程,以及官方未提到的點。
vue-easy-lightbox 是Vue2.x+TypeScript編寫的組件庫,.vue單文件使用的是vue-property-decorator ,由于Vue3.0原生支持了ts,直接改寫為官方推薦寫法(TypeScript 支持 - 定義 Vue 組件)。
Props類型聲明
Vue 對定義了 type 的 prop 執(zhí)行運行時驗證,我們通常需要為props聲明運行時構(gòu)造函數(shù)類型:
import { defineComponent, PropType } from 'vue'
interface ComplexItem {
title: string
id: number
}
// 建議業(yè)務(wù)中注明 default / required
const Component = defineComponent({
props: {
list: {
type: Array,
default: () => [],
required: true
},
mixProps: {
type: [Array, String]
},
item: {
// 如果一個prop需要具體類型,通過官方的泛型接口PropType強(qiáng)制轉(zhuǎn)換類型
type: Object as PropType<ComplexItem>
},
mixListAndString: {
// 如果type接受的是數(shù)組,需要將整個數(shù)組強(qiáng)制轉(zhuǎn)換類型
// 注意,不是將單個數(shù)組成員類型轉(zhuǎn)換
type: [Array, String] as PropType<ComplexItem[] | string>
}
},
methods: {
testProps() {
this.list // (property) list: unknown[]
this.mixProps // (property) mixProp?: string | unknown[] | undefined
this.item // (property) item?: ComplexItem | undefined
this.mixListAndString // (property) mixListAndString?: string | ComplexItem[] | undefined
}
}
})
Vue 單文件中,Transition 組件的子元素檢查
Vue3.0 中, @vue/compile-sfc 模板編譯和dev運行時檢查都添加了 transtion子元素檢查:
- 模板編譯中,
transition子元素不允許多個組件或元素,否則編譯不通過,根據(jù)warnTransitionChildren.spec.ts 測試文件,如果需要多個分支,可以使用v-if+v-if-else來確定具體分支。 - 運行時檢查中,需要特別注意
transition子元素內(nèi)不能包含注釋(這個坑踩了整整2天),否則無法通過運行時編譯,導(dǎo)致組件不能正確渲染。