自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Vue3+TypeScript完整項目上手教程

開發(fā) 前端
TypeScript 是JS的一個超集,主要提供了類型系統(tǒng)和對ES6的支持,使用 TypeScript 可以增加代碼的可讀性和可維護性,在 react 和 vue 社區(qū)中也越來越多人開始使用TypeScript。從最近發(fā)布的 Vue3 正式版本來看, Vue3 的源碼就是用 TypeScript 編寫的,更好的 TypeScript 支持也是這一次升級的亮點。

一個完整的Vue3+Ts項目,支持.vue和.tsx寫法

項目地址:https://github.com/vincentzyc/vue3-demo.git

TypeScript 是JS的一個超集,主要提供了類型系統(tǒng)和對ES6的支持,使用 TypeScript 可以增加代碼的可讀性和可維護性,在 react 和 vue 社區(qū)中也越來越多人開始使用TypeScript。從最近發(fā)布的 Vue3 正式版本來看, Vue3 的源碼就是用 TypeScript 編寫的,更好的 TypeScript 支持也是這一次升級的亮點。當然,在實際開發(fā)中如何正確擁抱 TypeScript 也是遷移至 Vue3 的一個小痛點,這里就針對 Vue3 和 TypeScript 展開一些交流。 

 

96.8%的代碼都是TypeScript,支持的力度也是相當大💪

  • Vue3入口: https://github.com/vuejs/vue-next

項目搭建

在官方倉庫的 Quickstart 中推薦用兩種方式方式來構(gòu)建我們的 SPA 項目:

  • vite 
  1. npm init vite-app sail-vue3 # OR yarn create vite-app sail-vue3 
  • vue-cli 
  1. npm install -g @vue/cli # OR yarn global add @vue/clivue create sail-vue3# select vue 3 preset 

vite 是一個由原生ESM驅(qū)動的Web開發(fā)構(gòu)建工具,打開 vite 依賴的 package.json 可以發(fā)現(xiàn)在 devDependencies 開發(fā)依賴里面已經(jīng)引入了TypeScript ,甚至還有 vuex , vue-router , less , sass 這些本地開發(fā)經(jīng)常需要用到的工具。vite 輕量,開箱即用的特點,滿足了大部分開發(fā)場景的需求,作為快速啟動本地 Vue 項目來說,這是一個非常完美的工具。

后面的演示代碼也是用vite搭的

從 vue2.x 走過來的掘友肯定知道 vue-cli 這個官方腳手架, vue3 的更新怎么能少得了 vue-cli 呢, vue-cli 更強調(diào)的是用 cli 的方式進行交互式的配置,選擇起來更加靈活可控。豐富的官方插件適配,GUI的創(chuàng)建管理界面,標準化開發(fā)流程,這些都是 vue-cli 的特點。

  • vue-cli ✖ TypeScript STEP1  

 

  • vue-cli ✖ TypeScript STEP2

 

 

想要預裝TypeScript,就需要選擇手動配置,并check好TypeScript

忘記使用選擇 TypeScript 也沒事,加一行cli命令就行了 

  1. vue add typescript 

最后,別忘了在 .vue 代碼中,給 script 標簽加上 lang="ts"

  1. <script lang="ts" 

Option API風格

在 Vue2.x 使用過 TypeScript 的掘友肯定知道引入 TypeScript 不是一件簡單的事情:

  1. 要用 vue-class-component 強化 vue 組件,讓 Script 支持 TypeScript 裝飾器
  2. 用 vue-property-decorator 來增加更多結(jié)合 Vue 特性的裝飾器
  3. 引入 ts-loader 讓 webpack 識別 .ts .tsx 文件
  4. ..... 

然后出來的代碼風格是這樣的:

  1. @Component({ 
  2.     components:{ componentA, componentB}, 
  3. }) 
  4. export default class Parent extends Vue{ 
  5.   @Prop(Number) readonly propA!: number | undefined 
  6.   @Prop({ default'default value' }) readonly propB!: string 
  7.   @Prop([String, Boolean]) readonly propC!: string | boolean | undefined 
  8.  
  9.   // data信息 
  10.   message = 'Vue2 code style' 
  11.  
  12.   // 計算屬性 
  13.   private get reversedMessage (): string[] { 
  14.       return this.message.split(' ').reverse().join(''
  15.   } 
  16.  
  17.   // method 
  18.   public changeMessage (): void { 
  19.     this.message = 'Good bye' 
  20.   } 

class 風格的組件,各種裝飾器穿插在代碼中,有點感覺自己不是在寫 vue ,些許凌亂🙈,所以這種曲線救國的方案在 vue3 里面肯定是行不通的。 

在 vue3 中可以直接這么寫: 

  1. import { defineComponent, PropType } from 'vue' 
  2.  
  3. interface Student { 
  4.   name: string 
  5.   class: string 
  6.   age: number 
  7.  
  8. const Component = defineComponent({ 
  9.   props: { 
  10.     success: { type: String }, 
  11.     callback: { 
  12.       type: Function as PropType<() => void> 
  13.     }, 
  14.     student: { 
  15.       type: Object as PropType<Student>, 
  16.       required: true 
  17.     } 
  18.   }, 
  19.   data() { 
  20.      return { 
  21.         message: 'Vue3 code style' 
  22.     } 
  23.   }, 
  24.   computed: { 
  25.     reversedMessage(): string { 
  26.       return this.message.split(' ').reverse().join(''
  27.     } 
  28.   } 
  29. }) 

vue 對 props 進行復雜類型驗證的時候,就直接用 PropType 進行強制轉(zhuǎn)換, data 中返回的數(shù)據(jù)也能在不顯式定義類型的時候推斷出大多類型, computed 也只用返回類型的計算屬性即可,代碼清晰,邏輯簡單,同時也保證了 vue 結(jié)構(gòu)的完整性。

Composition API風格

在 vue3 的 Composition API 代碼風格中,比較有代表性的api就是 ref 和 reactive ,我們看看這兩個是如何做類型聲明的:

ref

  1. import { defineComponent, ref } from 'vue' 
  2.  
  3. const Component = defineComponent({ 
  4. setup() { 
  5.   const year = ref(2020) 
  6.   const month = ref<string | number>('9'
  7.  
  8.   month.value = 9 // OK 
  9.   const result = year.value.split('') // => Property 'split' does not exist on type 'number' 
  10.  } 
  11. }) 

分析上面的代碼,可以發(fā)現(xiàn)如果我們不給定 ref 定義的類型的話, vue3 也能根據(jù)初始值來進行類型推導,然后需要指定復雜類型的時候簡單傳遞一個泛型即可。 

Tips:如果只有setup方法的話,可以直接在defineComponent中傳入setup函數(shù)

  1. const Component = defineComponent(() => { 
  2.     const year = ref(2020) 
  3.     const month = ref<string | number>('9'
  4.  
  5.     month.value = 9 // OK 
  6.     const result = year.value.split('') // => Property 'split' does not exist on type 'number' 
  7. }) 

reactive

  1. import { defineComponent, reactive } from 'vue' 
  2.  
  3. interface Student { 
  4.   name: string 
  5.   class?: string 
  6.   age: number 
  7.  
  8. export default defineComponent({ 
  9.   name'HelloWorld'
  10.   setup() { 
  11.     const student = reactive<Student>({ name'阿勇', age: 16 }) 
  12.     // or 
  13.     const student: Student = reactive({ name'阿勇', age: 16 }) 
  14.     // or 
  15.     const student = reactive({ name'阿勇', age: 16, class: 'cs' }) as Student 
  16.   } 
  17. }) 

聲明 reactive 的時候就很推薦使用接口了,然后怎么使用類型斷言就有很多種選擇了,這是 TypeScript 的語法糖,本質(zhì)上都是一樣的。

自定義Hooks

vue3 借鑒 react hooks 開發(fā)出了 Composition API ,那么也就意味著 Composition API 也能進行自定義封裝 hooks ,接下來我們就用 TypeScript 風格封裝一個計數(shù)器邏輯的 hooks ( useCount ): 

首先來看看這個 hooks 怎么使用:

  1. import { ref } from '/@modules/vue' 
  2. import  useCount from './useCount' 
  3.  
  4. export default { 
  5.   name'CountDemo'
  6.   props: { 
  7.     msg: String 
  8.   }, 
  9.   setup() { 
  10.     const { currentcount, inc, decset, reset } = useCount(2, { 
  11.       min: 1, 
  12.       max: 15 
  13.     }) 
  14.     const msg = ref('Demo useCount'
  15.  
  16.     return { 
  17.       count
  18.       inc, 
  19.       dec
  20.       set
  21.       reset, 
  22.       msg 
  23.     } 
  24.   } 

貼上 useCount 的源碼:

  1. import { ref, Ref, watch } from 'vue' 
  2.  
  3. interface Range { 
  4.   min?: number, 
  5.   max?: number 
  6.  
  7. interface Result { 
  8.   current: Ref<number>, 
  9.   inc: (delta?: number) => void, 
  10.   dec: (delta?: number) => void, 
  11.   set: (value: number) => void, 
  12.   reset: () => void 
  13.  
  14. export default function useCount(initialVal: number, range?: Range): Result { 
  15.   const current = ref(initialVal) 
  16.   const inc = (delta?: number): void => { 
  17.     if (typeof delta === 'number') { 
  18.       current.value += delta 
  19.     } else { 
  20.       current.value += 1 
  21.     } 
  22.   } 
  23.   const dec = (delta?: number): void => { 
  24.     if (typeof delta === 'number') { 
  25.       current.value -= delta 
  26.     } else { 
  27.       current.value -= 1 
  28.     } 
  29.   } 
  30.   const set = (value: number): void => { 
  31.     current.value = value 
  32.   } 
  33.   const reset = () => { 
  34.     current.value = initialVal 
  35.   } 
  36.  
  37.   watch(current, (newVal: number, oldVal: number) => { 
  38.     if (newVal === oldVal) return 
  39.     if (range && range.min && newVal < range.min) { 
  40.       current.value = range.min 
  41.     } else if (range && range.max && newVal > range.max) { 
  42.       current.value = range.max 
  43.     } 
  44.   }) 
  45.  
  46.   return { 
  47.     current
  48.     inc, 
  49.     dec
  50.     set
  51.     reset 
  52.   } 

分析源碼 

這里首先是對 hooks 函數(shù)的入?yún)㈩愋秃头祷仡愋瓦M行了定義,入?yún)⒌?Range 和返回的 Result 分別用一個接口來指定,這樣做了以后,最大的好處就是在使用 useCount 函數(shù)的時候,ide就會自動提示哪些參數(shù)是必填項,各個參數(shù)的類型是什么,防止業(yè)務邏輯出錯。

接下來,在增加 inc 和減少 dec 的兩個函數(shù)中增加了 typeo 類型守衛(wèi)檢查,因為傳入的 delta 類型值在某些特定場景下不是很確定,比如在 template 中調(diào)用方法的話,類型檢查可能會失效,傳入的類型就是一個原生的 Event 。

關(guān)于 ref 類型值,這里并沒有特別聲明類型,因為 vue3 會進行自動類型推導,但如果是復雜類型的話可以采用類型斷言的方式:ref(initObj) as Ref

小建議

AnyScript

在初期使用 TypeScript 的時候,很多掘友都很喜歡使用 any 類型,硬生生把TypeScript 寫成了 AnyScript ,雖然使用起來很方便,但是這就失去了 TypeScript 的類型檢查意義了,當然寫類型的習慣是需要慢慢去養(yǎng)成的,不用急于一時。

Vetur 

vetur 代碼檢查工具在寫vue代碼的時候會非常有用,就像構(gòu)建 vue 項目少不了 vue-cli 一樣,vetur 提供了 vscode 的插件支持,趕著升級 vue3 這一波工作,順帶也把 vetur 也帶上吧。

一個完整的Vue3+ts項目

├─public
│      favicon.ico
│      index.html
└─src
    │  App.vue
    │  main.ts
    │  shims-vue.d.ts
    ├─assets
    │  │  logo.png
    │  └─css
    │          base.css
    │          main.styl
    ├─components
    │  │  HelloWorld.vue
    │  └─base
    │          Button.vue
    │          index.ts
    │          Select.vue
    ├─directive
    │      focus.ts
    │      index.ts
    │      pin.ts
    ├─router
    │      index.ts
    ├─store
    │      index.ts
    ├─utils
    │  │  cookie.ts
    │  │  deep-clone.ts
    │  │  index.ts
    │  │  storage.ts
    │  └─validate
    │          date.ts
    │          email.ts
    │          mobile.ts
    │          number.ts
    │          system.ts
    └─views
        │  About.vue
        │  Home.vue
        │  LuckDraw.vue
        │  TodoList.vue
        └─address
                AddressEdit.tsx
                AddressList.tsx
  •  vue寫法
  1. <template> 
  2.   ... 
  3. </template> 
  4.  
  5. <script lang="ts"
  6. import dayjs from "dayjs"
  7. import { ref, reactive, onMounted } from "vue"
  8. import { Button, Step, Steps, NoticeBar } from "vant"
  9.  
  10. export default { 
  11.   components: { 
  12.     Button, 
  13.     Step, 
  14.     Steps, 
  15.     NoticeBar, 
  16.   }, 
  17.   setup() { 
  18.     const nameinput = ref(); 
  19.     const selectionStart = ref(0); 
  20.     const twoNow = dayjs().subtract(2, "day").format("YYYY-MM-DD HH:mm:ss"); 
  21.     const now = dayjs().format("YYYY-MM-DD HH:mm:ss"); 
  22.     const now2 = dayjs().add(2, "day").format("YYYY-MM-DD HH:mm:ss"); 
  23.     const formData = reactive({ 
  24.       name""
  25.       phone: ""
  26.       code: ""
  27.     }); 
  28.  
  29.     onMounted(() => { 
  30.       (nameinput.value as HTMLInputElement).focus(); 
  31.     }); 
  32.  
  33.     const insertName = () => { 
  34.       const index = (nameinput.value as HTMLInputElement).selectionStart; 
  35.       if (typeof index !== "number"return
  36.       formData.name = 
  37.         formData.name.slice(0, index) + "哈哈" + formData.name.slice(index); 
  38.     }; 
  39.  
  40.     return { 
  41.       nameinput, 
  42.       formData, 
  43.       insertName, 
  44.       selectionStart, 
  45.       twoNow, 
  46.       now, 
  47.       now2, 
  48.     }; 
  49.   }, 
  50. }; 
  51. </script>  
  1. <template> 
  2.    ... 
  3. </template> 
  4.  
  5. <script lang="ts"
  6. import dayjs from "dayjs"
  7. import { defineComponent } from "vue"
  8. import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src 
  9. import { Button, Dialog, Toast } from "vant"
  10.  
  11. export default defineComponent({ 
  12.   name"Home"
  13.   components: { 
  14.     HelloWorld, 
  15.     Button, 
  16.   }, 
  17.   data() { 
  18.     return { 
  19.       direction: "top"
  20.       pinPadding: 0, 
  21.       time""
  22.       timer: 0, 
  23.       color: "red"
  24.     }; 
  25.   }, 
  26.   methods: { 
  27.     showToast() { 
  28.       Toast("字體顏色已改藍色"); 
  29.       this.color = "blue"
  30.     }, 
  31.     handleClick() { 
  32.       Dialog({ 
  33.         title: "標題"
  34.         message: "這是一個全局按鈕組件"
  35.       }); 
  36.     }, 
  37.     initTime() { 
  38.       this.time = dayjs().format("YYYY-MM-DD HH:mm:ss"); 
  39.       this.timer = setInterval(() => { 
  40.         this.time = dayjs().format("YYYY-MM-DD HH:mm:ss"); 
  41.       }, 1000); 
  42.     }, 
  43.   }, 
  44.   created() { 
  45.     this.initTime(); 
  46.   }, 
  47.   beforeUnmount() { 
  48.     clearInterval(this.timer); 
  49.   }, 
  50. }); 
  51. </script> 
  52.  
  53. <style vars="{ color }"
  54. .text-color { 
  55.   color: var(--color); 
  56. </style> 
  •  tsx寫法 
  1. import { ref, reactive } from "vue"
  2. import { AddressList, NavBar, Toast, Popup } from "vant"
  3. import AddressEdit from './AddressEdit' 
  4. import router from '@/router' 
  5.  
  6. export default { 
  7.   setup() { 
  8.     const chosenAddressId = ref('1'
  9.     const showEdit = ref(false
  10.  
  11.     const list = reactive([ 
  12.       { 
  13.         id: '1'
  14.         name'張三'
  15.         tel: '13000000000'
  16.         address: '浙江省杭州市西湖區(qū)文三路 138 號東方通信大廈 7 樓 501 室'
  17.         isDefault: true
  18.       }, 
  19.       { 
  20.         id: '2'
  21.         name'李四'
  22.         tel: '1310000000'
  23.         address: '浙江省杭州市拱墅區(qū)莫干山路 50 號'
  24.       }, 
  25.     ]) 
  26.     const disabledList = reactive([ 
  27.       { 
  28.         id: '3'
  29.         name'王五'
  30.         tel: '1320000000'
  31.         address: '浙江省杭州市濱江區(qū)江南大道 15 號'
  32.       }, 
  33.     ]) 
  34.  
  35.     const onAdd = () => { 
  36.       showEdit.value = true 
  37.     } 
  38.     const onEdit = (item: anyindex: string) => { 
  39.       Toast('編輯地址:' + index); 
  40.     } 
  41.  
  42.     const onClickLeft = () => { 
  43.       router.back() 
  44.     } 
  45.  
  46.     const onClickRight = () => { 
  47.       router.push('/todoList'
  48.     } 
  49.  
  50.     return () => { 
  51.       return ( 
  52.         <div style="background:#f7f8fa"
  53.           <NavBar 
  54.             title="地址管理" 
  55.             left-text="返回" 
  56.             right-text="Todo" 
  57.             left-arrow 
  58.             onClick-left={onClickLeft} 
  59.             onClick-right={onClickRight} 
  60.           /> 
  61.           <AddressList 
  62.             vModel={chosenAddressId.value} 
  63.             list={list} 
  64.             disabledList={disabledList} 
  65.             disabledText="以下地址超出配送范圍" 
  66.             defaultTagText="默認" 
  67.             onAdd={onAdd} 
  68.             onEdit={onEdit} 
  69.           /> 
  70.           <Popup vModel={[showEdit.value, 'show']} position="bottom" round style="height: 80%" > 
  71.             <AddressEdit /> 
  72.           </Popup> 
  73.         </div > 
  74.       ); 
  75.     }; 
  76.   } 
  77. }; 

結(jié)束

不知不覺, Vue 都到3的One Piece時代了, Vue3 的新特性讓擁抱 TypeScript 的姿勢更加從容優(yōu)雅, Vue 面向大型項目開發(fā)也更加有底氣了,點擊查看更多。

責任編輯:龐桂玉 來源: 前端教程
相關(guān)推薦

2022-06-21 12:09:18

Vue差異

2021-05-26 10:40:28

Vue3TypeScript前端

2021-11-19 09:29:25

項目技術(shù)開發(fā)

2021-10-29 07:47:35

Vue 3teleport傳送門組件

2021-03-22 05:58:22

Vite2TypeScript4Vue3

2020-09-17 07:08:04

TypescriptVue3前端

2024-09-06 08:02:52

2023-03-13 07:52:13

2020-11-06 08:54:43

Vue 3.0函數(shù)代碼

2021-03-30 08:05:39

Vue 3 生命周期Vue2

2021-09-15 07:56:32

TypeScriptVue項目

2020-09-29 08:26:17

Vue3中新增的API

2011-09-27 11:30:29

SSH 環(huán)境搭建

2021-09-26 00:24:58

開發(fā)項目TypeScript

2022-02-18 09:39:51

Vue3.0Vue2.0Script Set

2009-09-25 10:24:40

Androind入門教OPhone

2024-11-06 10:22:23

Akamai云計算虛擬專用云

2020-03-25 18:23:07

Vue2Vue3組件

2013-12-04 13:27:56

Android SDK項目

2013-12-26 15:40:33

Android SDK項目
點贊
收藏

51CTO技術(shù)棧公眾號