前言
因為最近公司的團隊熱衷于vue框架,新項目想著練練typescript,于是開始了vue+ts的踩坑之路...本文意在為和我有一樣想法的伙伴們省去踩坑的時間,下面話不多說了,來一起看看關于Vue2 Vue-cli中利用Typescript需要的配置是什么吧。
一、初步配置
首先安裝官方插件vue-class-component,vue-property-decorator,配置webpack。
webpack配置如下:
修改入口文件
entry: { app: './src/main.ts'}resolve部分:
extensions: ['.js', '.vue', '.json', '.ts', '.tsx']
配置loader
{ test: //.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { appendTsSuffixTo: [//.vue$/], } }配置tsconfig.json
{ "include": [ "src/**/*" ], "exclude": [ "node_modules" ], "compilerOptions": { "allowSyntheticDefaultImports": true, "experimentalDecorators": true, "allowJs": true, "module": "es2015", "target": "es5", "moduleResolution": "node", "experimentalDecorators": true, "isolatedModules": true, "lib": [ "dom", "es5", "es2015.promise" ], "sourceMap": true, "pretty": true }}二、實戰!
配好配置只是第一步,在項目里跑起來才是王道。
在vue文件的script標簽里添加lang='ts'
因為ts-loader不像配過loader的webpack一樣知道vue,html等文件是什么東西,你跑起來后會報模塊無法解析的錯誤,所以還需要配置.d.ts聲明文件
vue的如下配置
declare module "*.vue" { import Vue from 'vue'; export default Vue;}你也可以為其它的非js模塊配置.d.ts文件如html(告訴ts-loader把html理解成字符串)
declare module "*.html" { let template: string; export default template;}配置好之后ts就能理解這些模塊了
從vue-property-decorator引入需要用到的模塊
(一般只用到Component, Vue, Watch, Prop這四個,其它3個沒用到也沒研究,知道的大佬可以解釋下。)
import { Component, Vue, Watch } from 'vue-property-decorator'
這里拿之前寫的sidbar的代碼當個栗子:
class HoverTopElem { leaveTop: number = -200 top: number = null height: number = null show(e) { this.top = e.target.getBoundingClientRect().top this.height = e.target.clientHeight } hidden() { this.top = this.leaveTop }}@Component({ name: 'sidebar', template: template, components: { sidebarItem }})export default class Sidebar extends Vue { SidebarMenu: any = SidebarMenu hoverTopElem: HoverTopElem = new HoverTopElem() activeListItemName: string = null activeRouteItemRoute: string = null get _activeRouteItemRoute(): string { return this.$route.path } @Watch('_activeRouteItemRoute', { immediate: true }) onRouteChanged(val: any) { this.activeRouteItemRoute = val } changeList(param) { this.activeListItemName = param } changeRoute(param) { this.activeRouteItemRoute = param }}
新聞熱點
疑難解答
圖片精選