前言
早在去年vue
官方已经支持了脚手架生成TypeScript
项目了,加上即将到来的vue3
是用TS
编写的。
故开始尝试现有项目的重构 此文为vue2.x
+ TypeScript
记录文,我会将踩过的坑一一记录。
对 TS 还未了解的可以参考这位前辈的文章,文章写的非常详细
点这里-Typescript 教程
1.刚上手就遇到一个大坑
如何在 TS 中使用全局变量
具体用法和 js 版本的一样
- 官方推荐使用全局变量专用模块
// 新建一个ts文件
// config.ts
export default {
install: (Vue: any, options: any) => {
Vue.prototype.api = {
testApi: 'xxxxxxxxx',
}
}
}
// 在main.ts中引入
import config from './config'
Vue.use(config)
- 个人喜欢使用的方式
// 新建一个ts文件
// config.ts
interface ApiType {
[apiName: string]: any
}
const api: ApiType = {
testApi: 'xxxxxxxxx'
}
export default api
// 在main.ts中引入
import config from './config'
Vue.prototype.config = config
两种方式都是将全局变量挂载到原型链,区别不大
本以为可以直接在 vue
文件中通过this
的方式调用,结果发现报错了
<script lang='ts'>
import { Component, Vue } from 'vue-property-decorator'
@Component
export default class App extends Vue {
private created() {
console.log(this.config.testApi) // Error:Property 'config' does not exist on type 'App'
}
}
</script>
在网上找了一圈找到解决方案 新建一个.d.ts
的文件名字随意 添加以下代码
//vue-prototype.d.ts
declare module 'vue/types/vue' {
interface Vue {
config: any
}
}
结果毫无作用,自信满满的重新编译,一看结果还是报错,百度google一番后被告知重启编辑器解决,在重启编辑器后依然如此,心态已崩。在盯着这个 interface Vue 半天后突然想到,这个Vue是从哪里来的?是不是需要引入?试了一下果然如此,编辑器正常了。吐血三升,吐槽一下某些文章写的一点都不严谨,代码缺少关键部分导致很多人踩坑,正常是这个样子
//vue-prototype.d.ts
import Vue from 'vue'
declare module 'vue/types/vue' {
interface Vue {
config: any
}
}
本文使用 mdnice 排版