Vue3+TypeScript完整項目上手教程

2022-01-08 前端學習棧
一個完整的Vue3+Ts項目,支持.vue和.tsx寫法

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

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

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

Vue3入口: https://github.com/vuejs/vue-next項目搭建

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

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

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

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

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

vue-cli ✖ TypeScript STEP1vue-cli ✖ TypeScript STEP2

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

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

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

Option API風格

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

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

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

@Component({
    components:{ componentA, componentB},
})
export default class Parent extends Vue{
  @Prop(Number) readonly propA!: number | undefined
  @Prop({ default: 'default value' }) readonly propB!: string
  @Prop([String, Boolean]) readonly propC!: string | boolean | undefined

  // data信息
  message = 'Vue2 code style'

  // 計算屬性
  private get reversedMessage (): string[] {
      return this.message.split(' ').reverse().join('')
  }

  // method
  public changeMessage (): void {
    this.message = 'Good bye'
  }
}

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

在 vue3 中可以直接這麼寫:

import { defineComponent, PropType } from 'vue'

interface Student {
  name: string
  class: string
  age: number
}

const Component = defineComponent({
  props: {
    success: { type: String },
    callback: {
      type: Function as PropType<() => void>
    },
    student: {
      type: Object as PropType,
      required: true
    }
  },
  data() {
     return {
        message: 'Vue3 code style'
    }
  },
  computed: {
    reversedMessage(): string {
      return this.message.split(' ').reverse().join('')
    }
  }
})

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

Composition API風格

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

refimport { defineComponent, ref } from 'vue'

const Component = defineComponent({
setup() {
  const year = ref(2020)
  const month = ref('9')

  month.value = 9 // OK
  const result = year.value.split('') // => Property 'split' does not exist on type 'number'
 }
})

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

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

const Component = defineComponent(() => {
    const year = ref(2020)
    const month = ref('9')

    month.value = 9 // OK
    const result = year.value.split('') // => Property 'split' does not exist on type 'number'
})
reactiveimport { defineComponent, reactive } from 'vue'

interface Student {
  name: string
  class?: string
  age: number
}

export default defineComponent({
  name: 'HelloWorld',
  setup() {
    const student = reactive({ name: '阿勇', age: 16 })
    // or
    const student: Student = reactive({ name: '阿勇', age: 16 })
    // or
    const student = reactive({ name: '阿勇', age: 16, class: 'cs' }) as Student
  }
})

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

自定義Hooks

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

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

import { ref } from '/@modules/vue'
import  useCount from './useCount'

export default {
  name: 'CountDemo',
  props: {
    msg: String
  },
  setup() {
    const { current: count, inc, dec, set, reset } = useCount(2, {
      min: 1,
      max: 15
    })
    const msg = ref('Demo useCount')

    return {
      count,
      inc,
      dec,
      set,
      reset,
      msg
    }
  }
}

出來的效果就是:

貼上 useCount 的源碼:

import { ref, Ref, watch } from 'vue'

interface Range {
  min?: number,
  max?: number
}

interface Result {
  current: Ref,
  inc: (delta?: number) => void,
  dec: (delta?: number) => void,
  set: (value: number) => void,
  reset: () => void
}

export default function useCount(initialVal: number, range?: Range): Result {
  const current = ref(initialVal)
  const inc = (delta?: number): void => {
    if (typeof delta === 'number') {
      current.value += delta
    } else {
      current.value += 1
    }
  }
  const dec = (delta?: number): void => {
    if (typeof delta === 'number') {
      current.value -= delta
    } else {
      current.value -= 1
    }
  }
  const set = (value: number): void => {
    current.value = value
  }
  const reset = () => {
    current.value = initialVal
  }

  watch(current, (newVal: number, oldVal: number) => {
    if (newVal === oldVal) return
    if (range && range.min && newVal < range.min) {
      current.value = range.min
    } else if (range && range.max && newVal > range.max) {
      current.value = range.max
    }
  })

  return {
    current,
    inc,
    dec,
    set,
    reset
  }
}

分析源碼

這裡首先是對 hooks 函數的入參類型和返回類型進行了定義,入參的 Range 和返回的 Result 分別用一個接口來指定,這樣做了以後,最大的好處就是在使用 useCount 函數的時候,ide就會自動提示哪些參數是必填項,各個參數的類型是什麼,防止業務邏輯出錯。

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

關於 ref 類型值,這裡並沒有特別聲明類型,因為 vue3 會進行自動類型推導,但如果是複雜類型的話可以採用類型斷言的方式:ref(initObj) as Ref

小建議 💡

AnyScript

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

Vetur

vetur 代碼檢查工具在寫vue代碼的時候會非常有用,就像構建 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

  ...


<script lang="ts">
import dayjs from "dayjs";
import { ref, reactive, onMounted } from "vue";
import { Button, Step, Steps, NoticeBar } from "vant";

export default {
  components: {
    Button,
    Step,
    Steps,
    NoticeBar,
  },
  setup() {
    const nameinput = ref();
    const selectionStart = ref(0);
    const twoNow = dayjs().subtract(2, "day").format("YYYY-MM-DD HH:mm:ss");
    const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
    const now2 = dayjs().add(2, "day").format("YYYY-MM-DD HH:mm:ss");
    const formData = reactive({
      name: "",
      phone: "",
      code: "",
    });

    onMounted(() => {
      (nameinput.value as HTMLInputElement).focus();
    });

    const insertName = () => {
      const index = (nameinput.value as HTMLInputElement).selectionStart;
      if (typeof index !== "number") return;
      formData.name =
        formData.name.slice(0, index) + "哈哈" + formData.name.slice(index);
    };

    return {
      nameinput,
      formData,
      insertName,
      selectionStart,
      twoNow,
      now,
      now2,
    };
  },
};


   ...


<script lang="ts">
import dayjs from "dayjs";
import { defineComponent } from "vue";
import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src
import { Button, Dialog, Toast } from "vant";

export default defineComponent({
  name: "Home",
  components: {
    HelloWorld,
    Button,
  },
  data() {
    return {
      direction: "top",
      pinPadding: 0,
      time: "",
      timer: 0,
      color: "red",
    };
  },
  methods: {
    showToast() {
      Toast("字體顏色已改藍色");
      this.color = "blue";
    },
    handleClick() {
      Dialog({
        title: "標題",
        message: "這是一個全局按鈕組件",
      });
    },
    initTime() {
      this.time = dayjs().format("YYYY-MM-DD HH:mm:ss");
      this.timer = setInterval(() => {
        this.time = dayjs().format("YYYY-MM-DD HH:mm:ss");
      }, 1000);
    },
  },
  created() {
    this.initTime();
  },
  beforeUnmount() {
    clearInterval(this.timer);
  },
});


<style vars="{ color }">
.text-color {
  color: var(--color);
}

import { ref, reactive } from "vue";
import { AddressList, NavBar, Toast, Popup } from "vant";
import AddressEdit from './AddressEdit'
import router from '@/router'

export default {
  setup() {
    const chosenAddressId = ref('1')
    const showEdit = ref(false)

    const list = reactive([
      {
        id: '1',
        name: '張三',
        tel: '13000000000',
        address: '浙江省杭州市西湖區文三路 138 號東方通信大廈 7 樓 501 室',
        isDefault: true,
      },
      {
        id: '2',
        name: '李四',
        tel: '1310000000',
        address: '浙江省杭州市拱墅區莫幹山路 50 號',
      },
    ])
    const disabledList = reactive([
      {
        id: '3',
        name: '王五',
        tel: '1320000000',
        address: '浙江省杭州市濱江區江南大道 15 號',
      },
    ])

    const onAdd = () => {
      showEdit.value = true
    }
    const onEdit = (item: any, index: string) => {
      Toast('編輯地址:' + index);
    }

    const onClickLeft = () => {
      router.back()
    }

    const onClickRight = () => {
      router.push('/todoList')
    }

    return () => {
      return (
        


          <navbar
            title="地址管理"
            left-text="返回"
            right-text="Todo"
            left-arrow
            onClick-left={onClickLeft}
            onClick-right={onClickRight}
          />
          <addresslist
            vModel={chosenAddressId.value}
            list={list}
            disabledList={disabledList}
            disabledText="以下地址超出配送範圍"
            defaultTagText="默認"
            onAdd={onAdd}
            onEdit={onEdit}
          />
          
            
          
        
      );
    };
  }
};

結束

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


相關焦點

  • 你知道vue項目怎麼使用TypeScript嗎?
    ③ 代碼提示:ts 搭配 vscode,代碼提示非常友好④代碼重構:例如全項目更改某個變量名(也可以是類名、方法名,甚至是文件名[重命名文件自動修改的是整個項目的import]),在JS中是不可能的,而TS可以輕鬆做到。
  • vue高級進階系列——用typescript玩轉vue和vuex
    本文轉載自【微信公眾號:趣談前端,ID:beautifulFront】經微信公眾號授權轉載,如需轉載與原文作者聯繫用過vue的朋友大概對vuex也不陌生,vuex的官方解釋是專為 Vue.js 應用程式開發的狀態管理模式。它採用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。
  • 面試官:說說如何在Vue項目中應用TypeScript?
    一、前言與如何在React項目中應用TypeScript類似在VUE項目中應用typescript,我們需要引入一個庫vue-property-decorator,其是基於vue-class-component庫而來,
  • Vue2.5+ Typescript 引入全面指南
    善對vuex支持後再考慮引入3. vue-property-decorator:非官方維護,一定學習成本4. vuex-class:非官方維護,在 vue-class-component 基礎上補充一定vuex支持(支持有限)5. vuex-ts-decorators/vuex-typescript等:非官方維護,學習成本極高PS: 後總結,vue
  • 實戰教學使用 Vue3 重構 Vue2 項目(萬字好文推薦)
    本文來自於 神奇的程式設計師 的分享好文,點擊閱讀原文查看作者的掘金鍊接。
  • 在 Vue3 + Vite + TS 項目中配置 ESLint,讓 VSCode 編輯器自動修復錯誤
    我通過 create-vite 腳手架創建的 Vue3 + TS 模板項目中沒有默認集成 ESLint 代碼檢查工具。通過查閱 ESLint 官方文檔和其他相關的博客後,我對 Vue3 + TS 項目從零配置 ESLint 寫了一篇總結。
  • Vue3.0+typescript+Vite+Pinia+Element-plus搭建vue3目前最流行的項目框架!
    隨著vue3.0的越來越受歡迎,開始有許多公司和個人開始學習並使用vue3開發項目。我從接觸學習並使用vue2,到現在的vue3,工作中也一直在使用vue。Vue3+Vite2+ts的項目模板,因此我們執行的命令是: yarn create vite my-vue-app --template vue-ts,這樣我們就不需要你單獨的再去安裝配置ts了。
  • Vue 3.0前的 TypeScript 最佳入門實踐
    然鵝最近的一個項目中,是 TypeScript+ Vue,毛計喇,學之...…真香!1、使用官方腳手架構建npm install -g @vue/cli# ORyarn global add @vue/cli新的 VueCLI工具允許開發者 使用 TypeScript 集成環境 創建新項目。
  • 最詳細從零開始配置 TypeScript 項目的教程
    了解 Vue CLI 3.x 的功能特點嗎?如何基於 Vue CLI 3.x 定製符合團隊項目的腳手架?工程化配置領域的設計可以有哪些設計階段(例如 react-scripts 和 vue ui 在設計以及使用形態上的區別)?工程化配置監控(使用版本信息、版本兼容性報錯信息分析、使用功能分析等)?
  • 最詳細的從零開始配置 TypeScript 項目的教程
    了解 Vue CLI 3.x 的功能特點嗎?如何基於 Vue CLI 3.x 定製符合團隊項目的腳手架?工程化配置領域的設計可以有哪些設計階段(例如 react-scripts 和 vue ui 在設計以及使用形態上的區別)?工程化配置監控(使用版本信息、版本兼容性報錯信息分析、使用功能分析等)?
  • 在Typescript項目中,如何優雅的使用ESLint和Prettier
    此外由於性能問題,TypeScript 官方決定全面採用ESLint,甚至把倉庫作為測試平臺,而 ESLint 的 TypeScript 解析器也成為獨立項目,專註解決雙方兼容性問題。  最近在我的項目的編碼規範中全量的用ESLint代替了TSLint,針對其中遇到的問題做一個記錄。
  • 或許是網上最詳細從零開始配置 TypeScript 項目的教程
    了解 Vue CLI 3.x 的功能特點嗎?如何基於 Vue CLI 3.x 定製符合團隊項目的腳手架?工程化配置領域的設計可以有哪些設計階段(例如 react-scripts 和 vue ui 在設計以及使用形態上的區別)?工程化配置監控(使用版本信息、版本兼容性報錯信息分析、使用功能分析等)?
  • TypeScript 中文入門教程
    於是在github上搜 TypeScript Handbook,果然有,翻譯的比較完整的有:既然大家都有翻譯了,那我也不必重新造輪子了,正打算放棄,突然一想,那中國那麼多想學習TypeScript的人,如果想入門豈不是和我遇到一樣的經歷,我至少知道Github,但很多初學者是不知道的,我要幫助後來者。
  • 前端開源實戰項目推薦
    項目地址:litemall Blog Vue Typescriptblog-vue-typescript 是基於 Vue + TypeScript + Element-Ui支持 markdown 渲染的博客前臺展示項目blog-vue-typescript PC 端效果圖
  • NodeJS:搭建vue+vuetify前端開發環境
    Vue 提供了支持 ts 的插件,在工程目錄下運行命令 vue add typescript 添加,配置選項筆者全選 Yes。✔  Successfully installed plugin: @vue/cli-plugin-typescript? Use class-style component syntax? Yes?
  • 想上手Vue2.0,不知道怎麼學效率最高?那就看這篇文章
    上手比較容易,但是也是有前提的。通讀官方教程 (guide) 的基礎篇。不要用任何構建工具,就只用最簡單的 script,把教程裡的例子模仿一遍,理解用法。不推薦上來就直接用 vue-cli 構建項目,尤其是如果沒有 Node/Webpack 基礎。照著官網上的示例,自己想一些類似的例子,模仿著實現來練手,加深理解。
  • Vue3+Vite+TS+Eslint(Airbnb規則)搭建生產項目,踩坑詳記(一):初始化,引入Airbnb
    前段時間領導告知公司將開啟一個全新的項目。從零開始,如果不嘗試一下最近火熱的 Vue3 + Vite 豈不是白白浪費了這麼好的吃螃蟹的機會。說幹就幹,然後就開始讀各種文檔,從 0 開始,一步一步搭完這個項目到可以正常開發,這對於我一個第一次搭生產項目的菜雞來說,著實艱難。到今天,項目已經進入聯調階段,並且已經在環境上部署成功可以正常訪問。這個實驗也算是有了階段性的成功吧,因此來寫文章記錄此次Vue3項目搭建歷險記。
  • 推薦9個優秀的 Vue 開源項目
    這對於初學者來說很容易上手;易於理解。由於其結構簡單,你可以輕鬆地把 Vue.js 添加到自己的 Web 項目裡。它憑藉定義良好的體系結構來保存你的數據。生命周期方法和自定義方法是分開的;輕鬆的集成。你可以通過 CDN 來輕鬆添加 Vue.js,不依賴 Node.js 和 npm 環境就可以用。
  • 深入理解 Vue 模板渲染:Vue 模板反編譯
    /* 作用域標識為 data-v-3fd7f12e */.effect-mask[data-v-3fd7f12e] {    opacity: 0;}// js 中肯定能找到對應的作用域標識,關聯某個組件,上面的 css 就是這個組件的 style
  • Vue 新版腳手架工具,300 行代碼輕盈新生!
    vite的Vue3項目。學會全新的官方腳手架工具 create-vue 的使用和原理2. 學會使用 VSCode 直接打開 github 項目3. 學會使用測試用例調試源碼4. 學以致用,為公司初始化項目寫腳手架工具。5. 等等2.