Vue+TypeScript使用summary创建一个新项目,可以安装vuecli3,通过vuecreate--global@vue/cli创建npminstall必须添加vue文件声明shims-vue.d。ts,在TypeScript中使用识别vue文件。内容可以参考下面的例子。1)ts默认不支持导入vue文件,需要通过下面的声明语句告诉ts根据VueConstructor处理vue文件的导入。因此,对vue文件的引用必须以.vue为后缀。2)当我们需要在Vue上挂载全局变量或方法时,例如Vue.prototype.$ajax=axios;需要在Vue接口上声明相应的变量_:任何;$实用程序:任何;}}declaremodule'*.vue'{exportdefaultVue}不用加shims-tsx.d.ts文件,在ts中使用jsx语法很方便。使用jsx语法和使用我们用模板编写的方式之间的主要区别在于您无法使用模板获得静态类型提示。配合babel-plugin-jsx-v-model插件,可以用jsx语法实现v-model使用TypeScript写Vue时,主要有两个方法:Vue.extend()和vue-class-component,两个methodsforscript部分添加属性lang=ts1)Vue.extend():使用基本的vue构造函数创建子类,和我们之前的vue写法很接近。只需用Vue.extend()包装组件内容。通过Vue.extend定义组件可以启用Vue的类型推断,类似下面的例子:importVuefrom'vue';exportdefaultVue.extend({name:'MyComponent',});2)vue-class-component:vue官方维护的装饰器,标有各种修饰符,可与vue-property-decorator结合使用importVuefrom'vue'importComponentfrom'vue-class-component'//@Component修饰符表示这个类是一个Vue组件@Component({template:''})exportdefaultclassMyComponentextendsVue{//初始数据可以直接声明为实例属性message:string\='Hello!'//组件方法也可以直接声明为实例方法onClick():void{window.alert(this.message)}}prop类型定义:1)ForArray,Objectmylist:Array,//错误的?。mylist:Arrayas()=>Array,//正确的写法?2)props中类型定义错误会影响后续对props和data中定义字段的引用,像"Property'xxx'这样的不存在于类型'Vue'上。”错误。vuex的使用,1)参考第一篇。[https://juejin.im/post/5c46c625e51d456e4138fa82](https://juejin.im/post/5c46c625e51d456e4138fa82)ii.[https://segmentfault.com/a/1190000011864013](https://segmentfault.com/a/1190000011864013)2)不推荐使用mapState/mapGetters/mapActions/mapMutations以明确指定类型。但是存储中的类型仍然会丢失。计算:{tags():Array{returnthis.$store.state.tags;},},eslint:1)基本的typescripteslint配置extends:\['@vue/typescript'\],rules:{//typescript-eslint规则'@typescript-eslint/indent':\['error',4\],'@typescript-eslint/explicit-function-return-type':0},parserOptions:{parser:'@typescript-eslint/parser'},2)如果遇到lint错误:e??slinttypescripttypeisdefined但从未使用过。添加以下lint配置覆盖:[{files:['*.ts','*.tsx','*.vue'],rules:{'@typescript-eslint/no-unused-vars':[2,{args:'none'}]}}]编译:使用命令vueaddtypescript,编译时会加入typescript编译。vueaddtypescript相当于npmi-D@vue/cli-plugin-typescript不需要我们设置webpackloader。Vue会自己处理tsvscode:1)vue文件中的ts使用声明的全局命名空间。vscode会提示找不到命名空间;但实际上编译是没有问题的,ts对声明类型的校验也没有问题。只能暂时不管了,还没找到好的解决办法。其他:1)webpackaliassetvue.config.js添加配置constpath=require("path");constresolve=dir=>path.resolve(__dirname,dir);module.exports={chainWebpack:config=>{config.resolve.alias.set("@",resolve(src));返回配置;}}tsconfig.json添加配置{"compilerOptions":{"paths":{"@/*":["src/*"]}}}配置完成后重启vscode生效部分错误处理:1)Module'lodashcanonlybedefault-importedusingthe'allowSyntheticDefaultImports'flagts(1259)解决方案:添加配置"allowSyntheticDefaultImports":truetotsconfig