TypeScript with Vue.js 3

Jason
4 min readOct 2, 2022

--

VSCODE 設定

除了裝 volar 還要關掉原本的 typescript 插建

take over mode 啟動

Typing Reactive Data

把 interface 獨立到一個檔案

引入時要加上 type 不然會跳紅字

Typing Refs

創建 Emoji type

引入使用

Typing Computed Props

因為是 string 所以噴錯,要是 number

Typing Event Handlers

  1. 有 global interface Event 可以用,不用 import
  2. 可以用 as 決定是哪種 HTML element

Declaring Component Events

在 Component Events 前面加上 @ 這樣就可以知道這是自己定義的事件

紀錄這個元件的自定義事件// runtime

有紀錄這樣 IDE 才會 autocomplete

Typing Component Events

紀錄這個元件的自定義事件// type-based

IDE 會跳提示 entry 有哪些東西可以用

當 entry 型別錯誤會被提醒

定義型別

Refactoring in TypeScript

製作一個 interface

將原本的型別定義改成剛才做的 interface

將需要更改的地方更改 ( 多了幾個屬性,更改 text 屬性變成 body)

將原本的型別定義改成剛才做的 interface

在 script 裡用 $emit

將原本的 $emit 改成函式

在 template 裡會自動 unwrap 但 script 裡要用 value

送出後清空

Declaring and Typing Component Props

外面

裡面

Typing Template Refs

在要操作的 DOM 上面增加 ref 屬性

onMounted 時操作 DOM

Typing Data Injected via Vue’s Provide/Inject

在 src 創建一個檔案, 用 symbol 產生一個 injectionKey

provide

inject

引入 inject 和 injectionKey 然後使用,IDE 會有提示

--

--

Jason
Jason

Written by Jason

Nothing is true, everything is permitted.

No responses yet