Vue3.0 踩坑實錄

原文發(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子元素檢查:

  1. 模板編譯中, transition 子元素不允許多個組件或元素,否則編譯不通過,根據(jù)warnTransitionChildren.spec.ts 測試文件,如果需要多個分支,可以使用 v-if + v-if-else 來確定具體分支。
  2. 運行時檢查中,需要特別注意 transition 子元素內(nèi)不能包含注釋(這個坑踩了整整2天),否則無法通過運行時編譯,導(dǎo)致組件不能正確渲染。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容