在Vue中使用Typescript

2,625 阅读1分钟

由于 Vue3将由 Typescript 重写,为了将来更好的迭代,这次的项目采用的是 Vue2+ + Typescript以求在 Vue3 出来的时候能够付出更少代价进行更迭。

结构

vue-cli 安装

npm install -g @vue/cli
vue create project

项目结构

├──node_modules // 依赖
├──public // 静态文件
├──src // 源目录
	├──api // api 统一管理
	├──assets // 静态资源
	├──components // 组件
	├──plugins // vue 插件
	├──route // vue-router
	├──store // vuex
	├──views // 页面
	├──App.vue // 页面入口
	├──element-variables.scss // element 全局变量
	├──index.d.ts // 第三方依赖注入声明
	├──main.ts // 主入口
	├──shims-tsx.d.ts // tsx 模块注入声明
	├──shims-vue.d.ts // vue 模块注入声明
├──.env.development // 开发环境变量
├──.env.production // 生成环境变量
├──.gitignore // git 排除文件
├──babel.config.js // bable 配置
├──package.json // npm 依赖管理
├──package-lock // npm 依赖记录
├──README.md // 项目描述
├──tsconfig.json // ts 配置
├──vue.config.js // vue 配置

用法

官方写法

import Vue from 'vue'
const Component = Vue.extend({
  // 类型推断已启用
})

const Component = {
  // 这里不会有类型推断,
  // 因为 TypeScript 不能确认这是 Vue 组件的选项
}

这是官方的写法,跟原来的写法差别不大,我不多做涉及。

vue-class-component

我们利用官方维护的装饰器库来以 class 的方式编写组件。

import { Component, Vue } from 'vue-property-decorator'

@Component
export default class Dnn extends Vue {}

第三方包声明

// api 封装
import api from './api'
Vue.prototype.$api = api
declare module 'vue/types/vue' {  
  interface Vue {  
    $api: any;
  }
}