栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

Vue-cli3项目引入Typescript的实现方法

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Vue-cli3项目引入Typescript的实现方法

前言

假设已经有一个通过 vue-cli3 脚手架构建的 vue 项目

命令行安装 Typescript

npm install --save-dev typescript
npm install --save-dev @vue/cli-plugin-typescript

编写 Typescript 配置

根目录下新建 tsconfig.json,下面为一份配置实例(点击查看所有配置项)。值得注意的是,默认情况下,ts 只负责静态检查,即使遇到了错误,也仅仅在编译时报错,并不会中断编译,最终还是会生成一份 js 文件。如果想要在报错时终止 js 文件的生成,可以在 tsconfig.json 中配置 noEmitonError 为 true。

{
 "compilerOptions": {
  "target": "esnext",
  "module": "esnext",
  "strict": true,
  "importHelpers": true,
  "moduleResolution": "node",
  "experimentalDecorators": true,
  "esModuleInterop": true,
  "allowSyntheticDefaultimports": true,
  "sourceMap": true,
  "baseUrl": ".",
  "allowJs": false,
  "noEmit": true,
  "types": [
   "webpack-env"
  ],
  "paths": {
   "@/*": [
    "src/*"
   ]
  },
  "lib": [
   "esnext",
   "dom",
   "dom.iterable",
   "scripthost"
  ]
 },
 "exclude": [
  "node_modules"
 ]
}

新增 shims-vue.d.ts

根目录下新建 shims-vue.d.ts,让 ts 识别 *.vue 文件,文件内容如下

declare module '*.vue' {
 import Vue from 'vue'
 export default Vue
}

修改入口文件后缀

src/main.js => src/main.ts

改造 .vue 文件

.vue 中使用 ts 实例

// 加上 lang=ts 让webpack识别此段代码为 typescript

一些好用的插件

vue-class-component:强化 Vue 组件,使用 Typescript装饰器 增强 Vue 组件,使得组件更加扁平化。点击查看更多

import Vue from 'vue'
import Component from 'vue-class-component'

// 表明此组件接受propMessage参数
@Component({
  props: {
    propMessage: String
  }
})
export default class App extends Vue {
  // 等价于 data() { return { msg: 'hello' } }
  msg = 'hello';
  
  // 等价于是 computed: { computedMsg() {} }
  get computedMsg() {
    return 'computed ' + this.msg
  }
  
  // 等价于 methods: { great() {} }
  great() {
    console.log(this.computedMsg())
  }
}

vue-property-decorator:在 vue-class-component 上增强更多的结合 Vue 特性的装饰。点击查看更多

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

@Component
export default class App extends Vue {
  @Prop(Number) readonly propA: Number | undefined
  @Prop({ type: String, default: ''}) readonly propB: String
  
  // 等价于 watch: { propA(val, oldval) { ... } }
  @Watch('propA')
  onPropAChanged(val: String, oldVal: String) {
    // ...
  }
  
  // 等价于 resetCount() { ... this.$emit('reset') }
  @Emit('reset')
  resetCount() {
    this.count = 0
  }
  
  // 等价于 returnValue() { this.$emit('return-value', 10, e) }
  @Emit()
  returnValue(e) {
    return 10
  }
  
  // 等价于 promise() { ... promise.then(value => this.$emit('promise', value)) }
  @Emit()
  promise() {
    return new Promise(resolve => {
      resolve(20)
    })
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/73049.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号