Vue3 结合 TypeScript 项目搭建与最佳实践指南

作者:青山有信时间:2026-10-25 09:42:21浏览:248

本文详解 Vue3 结合 TypeScript 的项目搭建流程,对比 Vite 与 vue-cli 两种构建工具。深入解析 Option API 与 Composition API 下的类型声明技巧,涵盖 ref、reactive 及自定义 Hooks 的类型定义。同时提供避免 AnyScript 的建议及 Vetur 工具配置,助力构建类型安全的大型 Vue3 应用。

TypeScript 作为 JavaScript 的超集,提供了强大的类型系统和 ES6 支持,能显著提升代码的可读性与可维护性。目前 React 和 Vue 社区中 TypeScript 的使用率日益增长。随着 Vue3 正式版本的发布,其源码完全采用 TypeScript 编写,对 TypeScript 的原生支持成为此次升级的核心亮点。然而,在实际迁移至 Vue3 时,如何正确且高效地集成 TypeScript 仍是一个值得探讨的课题。

一、项目搭建

Vue3 源码中高达 96.8% 的代码由 TypeScript 编写,这体现了框架对 TypeScript 的强力支持。

Vue3 官方仓库地址:https://github.com/vuejs/vue-next

一、项目搭建

在官方仓库的 Quickstart 文档中,推荐了两种构建单页应用(SPA)的方式:

vite

npm init vite-app sail-vue3 # OR yarn create vite-app sail-vue3

vue-cli

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 的支持,它更侧重于通过 CLI 进行交互式配置,使选择过程更加灵活可控。丰富的官方插件适配、GUI 创建管理界面以及标准化的开发流程,构成了 vue-cli 的主要特色。

vue-cli 集成 TypeScript 步骤一

一、项目搭建

vue-cli 集成 TypeScript 步骤二

一、项目搭建

若需预装 TypeScript,必须在配置过程中选择手动模式,并勾选 TypeScript 选项。

如果忘记在创建时选择 TypeScript,后续只需添加一行 CLI 命令即可补充支持。

vue add typescript

最后,请务必在 .vue 文件的 script 标签中设置 lang="ts",以启用 TypeScript 解析。

<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<Student>,
      required: true
    }
  },
  data() {
     return {
        message: 'Vue3 code style'
    }
  },
  computed: {
    reversedMessage(): string {
      return this.message.split(' ').reverse().join('')
    }
  }
})

Vue 对 props 进行复杂类型验证时,可直接使用 PropType 进行强制转换。data 中返回的数据即使不显式定义类型,Vue3 也能推断出大多数类型。computed 计算属性只需返回类型即可,代码逻辑清晰简洁,同时保证了 Vue 结构的完整性。

三、Composition API 风格

在 Vue3 的 Composition API 代码风格中,最具代表性的 API 是 ref 和 reactive。我们来看看这两个 API 如何进行类型声明:

ref

import { defineComponent, ref } from 'vue'
const Component = defineComponent({
setup() {
  const year = ref(2020)
  const month = ref<string | number>('9')
  month.value = 9 // OK
  const result = year.value.split('') // => Property 'split' does not exist on type 'number'
 }
})

分析上述代码可知,若未指定 ref 的类型,Vue3 会根据初始值自动进行类型推导。当需要指定复杂类型时,只需简单传递一个泛型即可。

提示:

如果组件仅包含 setup 方法,可以直接在 defineComponent 中传入 setup 函数。

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

reactive

import { defineComponent, reactive } from 'vue'
interface Student {
  name: string
  class?: string
  age: number
}
export default defineComponent({
  name: 'HelloWorld',
  setup() {
    const student = reactive<Student>({ 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<number>,
  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)的两个函数中增加了 typeof 类型守卫检查。因为传入的 delta 类型值在某些特定场景下不确定,例如在 template 中调用方法时,类型检查可能会失效,此时传入的类型可能为原生 Event。

关于 ref 类型的值,此处并未特别声明类型,因为 Vue3 会进行自动类型推导。但如果涉及复杂类型,可采用类型断言方式:ref(initObj) as Ref<ObjType>。

五、小建议

避免 AnyScript

在初期使用 TypeScript 时,许多开发者倾向于使用 any 类型,硬生生将 TypeScript 写成了 AnyScript。虽然这样使用便捷,但失去了 TypeScript 类型检查的意义。当然,编写类型的习惯需要逐步养成,不必急于求成。

Vetur 工具

Vetur 代码检查工具在编写 Vue 代码时非常有用。正如构建 Vue 项目离不开 vue-cli,Vetur 提供了 VSCode 插件支持。在升级 Vue3 的过程中,建议同时配置 Vetur 以提升开发体验。

一、项目搭建

六、一个完整的 Vue3 + TypeScript 项目

├─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 文件写法示例

<template>
  ...
</template>
 
<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>
<template>
   ...
</template>
<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);
  },
});
</script>
<style vars="{ color }">
.text-color {
  color: var(--color);
}
</style>

tsx 文件写法示例

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 (
        <div style="background:#f7f8fa">
          <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}
          />
          <Popup vModel={[showEdit.value, 'show']} position="bottom" round style="height: 80%" >
            <AddressEdit />
          </Popup>
        </div >
      );
    };
  }
};

七、总结

不知不觉,Vue 已进入 3.0 的 One Piece 时代。Vue3 的新特性使得拥抱 TypeScript 的姿态更加从容优雅,也让 Vue 面向大型项目开发时更加有信心。

到此,关于 Vue3 携手 TypeScript 搭建完整项目结构的介绍暂告一段落。更多相关 Vue3 与 TypeScript 的项目搭建内容,请搜索本站历史文章或继续浏览后续文章。希望大家以后多多支持本站!

作者最新文章
相关文章
更多