深入使用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. Android 直连SQL

    在工作中遇到需求需要Android直接连接SQL,看了一些人说不建议直连,但我对性能没有要求,甚至说只要在局域网内能够使用就行,简单说把手机当作一个简单的移动操作点. 代码的话,网上都有比如: htt ...

  2. luogu题解P2312解方程--暴力模+秦九韶

    题目链接 https://www.luogu.org/problemnew/show/P2312 分析 这道题很毒啊,这么大的数. 但是如果多项式\(\sum_{i=0}^N a[i]*X^i=0\) ...

  3. 关于servlet类,继承HttpServlet,但是无法导入HttpServlet包的原因和解决方法

    原因:缺少tomcat的libraries(HttpServlet对应位置在tomcat的lib中====) 解决: 1. 2. 3. 4.

  4. mysql float 精度丢失

    mysql 中保存了字段 float s=0.3 直接执行sql 查出来是 0.3 但是JPA 执行查询结果是 0.2999 换成decimal 就可以

  5. Linux下的打包操作

    范例一:将整个 test 目录下的文件全部打包成为 test.tar[python@master ~]$ tar -cvf test.tar test/         ==仅打包,不压缩!test/ ...

  6. Linux服务器性能检查教程

    一.uptime命令 这个命令可以快速查看机器的负载情况.在Linux系统中,这些数据表示等待CPU资源的进程和阻塞在不可中断IO进程(进程状态为D)的数量.这些数据可以让我们对系统资源使用有一个宏观 ...

  7. innodb存储引擎之内存

    1.innoDB存储引擎体系架构 如上图所示,innoDB存储是基于磁盘存储的,并且其中的记录以页的方式进行管理,但为什么要引入一个内存池呢? 其目的就是为了协调CUP速度与磁盘速度的鸿沟,基于磁盘的 ...

  8. springboot项目logback.xml或者logback-spring.xml中读取不到application.yml或application.properties配置文件中的配置解决办法

    在springboot项目中我们可能想要实现不同环境的日志项目配置不同,比如我想让不同环境的日志路径不同. 这时候我们很容易想: 1.到将日志路径配置在springboot的:application- ...

  9. 1.RPC原理学习

    1.什么是RPC:远程过程调用协议 RPC(Remote Procedure Call Protocol)— 远程过程调用协议,是一种通过网络从远程计算机程序上请求服务,而不需要 了解底层网络技术的协 ...

  10. “联邦对抗技术大赛”9月开战 微众银行呼唤开发者共同“AI创新”

    “联邦对抗技术大赛”9月开战  微众银行呼唤开发者共同“AI创新”   从<第五元素>中的智能系统到<超体>中的信息操控,在科幻电影中人工智能已经发展到了极致.而在现实中,目前 ...