【TypeScript】ts在vue中的使用

目录

一、Vue 3 + TypeScript 

1. 项目创建与配置

项目创建

 关键配置文件

2.完整项目结构示例

3. 组件 Props 类型定义

4. 响应式数据与 Ref

5. Composition 函数复用

二、组件开发

1.组合式API(Composition API)

2.选项式API(Options API)

三、Vue 2 + TypeScript

1. 安装依赖

2. 类组件(Vue Class Component)

3.Vuex类型安全

四、状态管理(Pinia + TypeScript)

1. 定义 Store

2. 在组件中使用

五、高级类型操作

1.全局属性扩展

2. 为无类型库添加声明

3.泛型组件

4.使用 Vue Router

六、最佳实践

严格类型检查:

类型导入:

避免 any:

性能优化

七、常见问题

Q1:模板中的类型检查

Q2:处理$refs类型

Q3:动态路由类型(Vue  Router)

Q2: 如何处理模板中的类型检查?

八、学习资源


一、Vue 3 + TypeScript 

Vue 3 原生支持 TypeScript,推荐使用 

4. 响应式数据与 Ref
5. Composition 函数复用
// composables/useCounter.ts
import { ref } from 'vue';

export default function useCounter(initialValue: number = 0) {
  const count = ref(initialValue);

  const increment = () => {
    count.value++;
  };

  return {
    count,
    increment
  };
}

// 在组件中使用

二、组件开发

1.组合式API(Composition API)


2.选项式API(Options API)




三、Vue 2 + TypeScript

Vue 2 需通过 vue-class-component 或 vue-property-decorator 增强类型支持。

1. 安装依赖
npm install vue-class-component vue-property-decorator --save
2. 类组件(Vue Class Component)


3.Vuex类型安全
// store/modules/user.ts
import { Module } from 'vuex';

interface UserState {
  name: string;
  age: number;
}

const userModule: Module = {
  namespaced: true,
  state: () => ({
    name: 'Alice',
    age: 30
  }),
  mutations: {
    SET_NAME(state, payload: string) {
      state.name = payload;
    }
  },
  actions: {
    updateName({ commit }, newName: string) {
      commit('SET_NAME', newName);
    }
  },
  getters: {
    fullInfo: (state) => `${state.name} (${state.age})`
  }
};

四、状态管理(Pinia + TypeScript)

Pinia 是 Vue 官方推荐的状态管理库,天然支持 TypeScript。

1. 定义 Store

// stores/counter.ts
import { defineStore } from 'pinia';

interface CounterState {
  count: number;
  lastUpdated?: Date;
}

export const useCounterStore = defineStore('counter', {
  state: (): CounterState => ({
    count: 0,
    lastUpdated: undefined
  }),
  actions: {
    increment() {
      this.count++;
      this.lastUpdated = new Date();
    }
  },
  getters: {
    doubleCount: (state) => state.count * 2
  }
});
2. 在组件中使用
 
  

五、高级类型操作

1.全局属性扩展
// src/types/global.d.ts
import { ComponentCustomProperties } from 'vue';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $formatDate: (date: Date) => string; // 全局方法
    $api: typeof import('./api').default; // 全局 API 实例
  }
}

// main.ts 中注入
app.config.globalProperties.$formatDate = (date: Date) => date.toLocaleString();
2. 为无类型库添加声明

创建 src/types/shims.d.ts

declare module 'untyped-vue-library' {
  export function doSomething(config: any): void;
}
3.泛型组件


4.使用 Vue Router
// router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';

const routes: Array = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue')
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

六、最佳实践

严格类型检查

在 tsconfig.json 中启用严格模式

{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": false // 可逐步开启
  }
}
类型导入

优先使用 TypeScript 类型导入:

import type { Router } from 'vue-router';
避免 any

尽量使用精确类型,仅在紧急情况下使用 any

性能优化

1.类型安全的异步组件

// 显式定义加载的组件类型
const AsyncModal = defineAsyncComponent({
  loader: () => import('./Modal.vue'),
  loadingComponent: LoadingSpinner,
  delay: 200
});

2.避免不必要的类型断言

// Bad: 过度使用 as
const data = response.data as User[];

// Good: 使用类型守卫
function isUserArray(data: any): data is User[] {
  return Array.isArray(data) && data.every(item => 'id' in item);
}
if (isUserArray(response.data)) {
  // 安全使用 response.data
}

七、常见问题

Q1:模板中的类型检查

安装Volar VS Code插件

禁用Vetur(避免冲突)

Q2:处理$refs类型
// main.ts
import { createApp } from 'vue';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $myGlobal: string;
  }
}

const app = createApp(App);
app.config.globalProperties.$myGlobal = 'hello';
Q3:动态路由类型(Vue  Router)
// router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';

declare module 'vue-router' {
  interface RouteMeta {
    requiresAuth?: boolean;
  }
}

const routes: RouteRecordRaw[] = [
  {
    path: '/user/:id',
    component: () => import('@/views/User.vue'),
    props: (route) => ({ id: Number(route.params.id) }) // 类型转换
  }
];

Q3: 如何为全局属性添加类型?

在 Vue 3 中:

// main.ts
import { createApp } from 'vue';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $myGlobal: string;
  }
}

const app = createApp(App);
app.config.globalProperties.$myGlobal = 'hello';
Q2: 如何处理模板中的类型检查?

Vue 3 的 Volar 插件(替代 Vetur)提供模板内类型检查,需在 VS Code 中安装。

八、学习资源

  1. Vue 3 + TypeScript 官方指南

  2. Pinia 官方文档

  3. Vue 3 TypeScript 示例项目

本文有待更新,暂时不为最终版本

码字不易,各位大佬点点赞

你可能感兴趣的:(#,TypeScript,typescript,vue.js,javascript)