深入使用TS

支持 render jsx 写法

这里一共分两步

  1. 首先得先让 vue 支持 jsx 写法

  2. 再让 vue 中的 ts 支持 jsx 写法

让 vue 支持 jsx

按照官方做法,安装Babel 插件

安装依赖

npm install\
babel-plugin-syntax-jsx\
babel-plugin-transform-vue-jsx\
babel-helper-vue-jsx-merge-props\
babel-preset-es2015\
--save-dev

.babelrc中添加:

{
"plugins": ["transform-vue-jsx"]
}

之后就可以这些写render,如下图:

让 ts 支持 jsx

首先配置 webpack
找到./build/webpack.base.conf.js

  • 找到resolve.extensions 里面加上.tsx 后缀

  resolve: {
extensions: ['.js', '.vue', '.json', '.ts', '.tsx']
}
  • 找到module.rules 修改webpack对.tsx .ts 的解析

  module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
// 从这里复制下面的代码就可以了
// 如果之前按照起手式配置的同学,请替换配置
{
test: /\.tsx?$/,
exclude: /node_modules/,
enforce: 'pre',
loader: 'tslint-loader'
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: Object.assign(vueLoaderConfig, {
loaders: {
ts: "ts-loader",
tsx: "babel-loader!ts-loader"
}
})
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
"babel-loader",
{
loader: "ts-loader",
options: { appendTsxSuffixTo: [/\.vue$/] }
}
]
},
// 复制截止
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},

上面的配置,主要意思是 vue 文件识别ts/tsx代码的时候,先过一遍ts-loader,在过一遍babel-loader,我知道这听起来有点蠢,但是jsx不能不要对吧?

然后在 tsconfig.json中,添加对jsx的支持

 "compilerOptions": {
"jsx": "preserve"
}

之后就可以顺利在.vue单文件中的tsjsx代码了,如下图所示:

敲黑板,这里又有重点,使用 jsx 写法的话, 一定要使用 .tsx,不要用.ts了,切记!!!

支持es6 / es7

在 tsconfig.json中,添加对es6 / es7的支持,更多的配置请见tsconfig - 编译选项

"lib": [
"dom",
"es5",
"es6",
"es7",
"es2015.promise"
]

不然的话,连Object.assign 这种最基本的函数也会在ts中报错,真的令人难过

配置 vuex

这里就比较简单了

# 安装依赖
npm i vuex vuex-class --save
  • vuex:在 vue 中集中管理应用状态

  • vuex-class :在 vue-class-component 写法中 绑定 vuex

Store的配置跟原来一模一样,引用的时候有一点区别,下面的例子介绍了用法,应该一看便知,这里我不做赘述

import Vue from 'vue'
import Component from 'vue-class-component'
import {
State,
Getter,
Action,
Mutation,
namespace
} from 'vuex-class' const ModuleGetter = namespace('path/to/module', Getter) @Component
export class MyComp extends Vue {
@State('foo') stateFoo
@State(state => state.bar) stateBar
@Getter('foo') getterFoo
@Action('foo') actionFoo
@Mutation('foo') mutationFoo
@ModuleGetter('foo') moduleGetterFoo // 如果省略了参数,使用属性名
// for each state/getter/action/mutation type
@State foo
@Getter bar
@Action baz
@Mutation qux created () {
this.stateFoo // -> store.state.foo
this.stateBar // -> store.state.bar
this.getterFoo // -> store.getters.foo
this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })
this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })
this.moduleGetterFoo // -> store.getters['path/to/module/foo']
}
}

让 vue 识别全局方法/变量

在项目中使用 ui 组件是很正常的操作

比如使用 Element-uI 的 meesage,用法如下图:

  this.$message({
message: '恭喜你,这是一条成功消息',
type: 'success'
})

但是在配置了 typescript之后

那是因为 $message属性,并没有在 vue实例中声明

解决办法也非常简单,那我们就声明一下呗

在之前文章中创建的 src/vue-shim.d.ts文件中,增加如下代码:

// 声明全局方法
declare module 'vue/types/vue' {
interface Vue {
$Message: any,
$Modal: any
}
}

这样,之后再使用this.$message()的话就不会报错了

支持 mixin

我在vue-property-decorator里里外外找了好几圈,缺没有找到mixin这个修饰器

 // 如果全局mixin,那也太蠢了
Vue.mixin( mixin )

找非常多的 ts + vue 项目,但是没有找到我理想的mixin的方式,
那么就自己进行探索咯,下图是我自己使用的目前最佳mixin方式:

声明了一个mixin组件,如下图:

其实就是我在mixin中声明了声明属性 / 方法,那么我就在vue实例中声明这个属性 / 方法

使用方式如下图:

支持 ProvidePlugin 的全局变量,比如 lodash 的 _

如果我们在项目中有使用 jquery,lodash 这样的工具库的时候,肯定不希望在所有用到的地方都import _ from ‘lodash’
@types/lodash

那我们就来配置一下:

首先还是在webpack.base.conf.js 中添加一个插件、并把这个 vendor拉出来

  entry: {
app: './src/main.ts',
vendor: [
"lodash"
]
} plugins: [
new webpack.ProvidePlugin({
_: 'lodash'
})
]
 

上面的意思是,当模块使用这些变量的时候wepback会自动加载

然后,你需要告诉eslint这个 _ 是全局的

.eslintrc.js中添加

  globals: {
_: true
},

接下来,你还需要告诉ts这个 _ 是全局的

vue-shim.d.ts

declare global {
const _: typeof lodash
}

如果没有上面这段声明,但是在 ts 中使用的话,会报如下的错误:

这个问题Consider allowing access to UMD globals from modules · Issue #10178 · Microsoft/TypeScript · GitHub

有一个很简单的解释,就是害怕你全局声明的_ 跟 import _ from 'lodash' 的行为不一致,这样的话,之后会留下隐患

深入使用Vue + TS的更多相关文章

  1. [Vue + TS] Watch for Changes in Vue Using the @Watch Decorator with TypeScript

    Vue watchers allow to perform async updates as a side effect of a property change. This lesson shows ...

  2. [Vue +TS] Use Two-Way Binding in Vue Using @Model Decorator with TypeScript

    Vue models, v-model, allow us to use two-way data binding, which is useful in some cases such as for ...

  3. [Vue + TS] Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript

    Vue 2.2 introduced a simple dependency injection system, allowing you to use provide and inject in y ...

  4. [Vue + TS] Use Properties in Vue Components Using @Prop Decorator with TypeScript

    With properties we can follow a one-way parent→child flow communication between components. This les ...

  5. [Vue + TS] Create Type-Safe Vue Directives in TypeScript

    Directives allow us to apply DOM manipulations as side effects. We’ll show you how you can create yo ...

  6. [Vue + TS] Using Route events inside Vue

    vue-router introduces new hooks into the component. In this lesson we’ll show you how to use these n ...

  7. [Vue + TS] Write a Vue Component as a Class in TypeScript

    Starter app: https://github.com/alexjoverm/Vue-Typescript-Starter Writing Vue components as plain ob ...

  8. 【vue&ts开发】Vue 3.0前的 TypeScript 最佳入门实践

    1.使用官方脚手架构建 新的 VueCLI工具允许开发者 使用 TypeScript 集成环境 创建新项目. 只需运行 vue createmy-app. 然后,命令行会要求选择预设.使用箭头键选择  ...

  9. vue + ts Vuex篇

    Vuex对Typescript的支持,仍十分薄弱,官方库只是添加了一些.d.ts声明文件,并没有像vue 2.5这样内置支持. 第三方衍生库 vuex-typescript, vuex-ts-deco ...

  10. vue+ts搭建项目

    Tip: 为了避免浪费您的时间,本文符合满足以下条件的同学借鉴参考 1.本文模版不适用于小型项目,两三个页面的也没必要用vue2.对typescript.vue全家桶能够掌握和运用 此次项目模版主要涉 ...

随机推荐

  1. thymeleaf 模板使用 之 前台界面获取后台属性值

    使用Thymeleaf模板时,如果需要在js中获取后台传值,那么需要用内联JS写法获取 [姿势很重要] 一.后台通过Model的addAttribute方法向前台传值 1.js获取后台属性值(--内联 ...

  2. js对象的 两种访问方式

    来对象访问属性有两种方式.有一个对象Obj = {"Name":"Langshen","AGE":"28"} 用点访问, ...

  3. VS2019 快捷键

    工欲善其事,必先利其器,整理了下VS最常用的快捷键,查看了不少资料,汇总了下,没有的自己补充,可以打印,用Excel编辑的. 可编辑版本下载:Excel文件下载 你可能需要查询其他的快捷键,MSDN介 ...

  4. MYSQL 增加语句(数据)

    增加数据     如果你失忆了,希望你能想起曾经为了追求梦想的你.     前一节我们学习了查询语句 SELECT,这节课,我们学习增加 INSERT INTO ****  VALUES ****,基 ...

  5. go语言时间函数

    以YY-mm-dd HH:MM:SS.9位 输出当前时间: func main() { fmt.Println(time.Now()) // 2019-11-15 16:26:12.4807588 + ...

  6. STM32WB AHB总线、APB总线与外设

    方框图: 如图所示: 1)APB1外设 2)APB2外设 3)AHB1外设 4)AHB2外设 5)AHB3外设 6)AHB4外设(ABH共享总线外设) 内存映射关系图:

  7. bootstrap和JS实现下拉菜单

    // bootstrap下拉菜单 <div class="btn-group"> <button id="button_text" type= ...

  8. AWK程序设计语言

    一. AWK入门指南 Awk是一种便于使用且表达能力强的程序设计语言,可应用于各种计算和数据处理任务.本章是个入门指南,让你能够尽快地开始编写你自己的程序.第二章将描述整个语言,而剩下的章节将向你展示 ...

  9. Acwing 197. 阶乘分解

    给定整数 N ,试把阶乘 N! 分解质因数,按照算术基本定理的形式输出分解结果中的 pipi 和 cici 即可. 输入格式 一个整数N. 输出格式 N! 分解质因数后的结果,共若干行,每行一对pi, ...

  10. CSS基础学习-10.CSS伸缩盒(老版本)