国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vue2 Vue-cli中使用Typescript的配置詳解

2024-05-06 15:13:56
字體:
來源:轉載
供稿:網友

前言

因為最近公司的團隊熱衷于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 }}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 和平区| 广水市| 民勤县| 元阳县| 齐齐哈尔市| 崇阳县| 黄浦区| 临西县| 彰化市| 根河市| 剑河县| 江津市| 六盘水市| 江津市| 饶平县| 来凤县| 惠州市| 叶城县| 措美县| 贺州市| 永康市| 台东市| 丘北县| 泌阳县| 克什克腾旗| 普兰店市| 九江市| 同德县| 桐乡市| 临沂市| 旺苍县| 道孚县| 西和县| 石泉县| 贵南县| 舟山市| 阳曲县| 大新县| 府谷县| 九龙县| 亳州市|