深入使用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. 修改源码去除zblog博客分类目录的RSS图标

    zblog博客的所建立的分类默认前面是有一个RSS图标的,如下图所示: 其实这个图标的存在并不能起到太大的美化作用,增加用户订阅数量的作用.那么应该如何去掉这个RSS图标呢? 这个RSS图标的生成在z ...

  2. Ubuntu14.04更新硬件实现堆栈(HWE)

    Ubuntu14.04更新硬件实现堆栈(HWE) 来源: https://github.com/gatieme/AderXCoding/tree/master/system/tools/ubuntu_ ...

  3. luogu题解 P3709 【大爷的字符串题】

    题目链接: https://www.luogu.org/problemnew/show/P3709 思路: 首先我是没读懂题目的,浏览了讨论区的dalao发现才知道就是求区间众数的出现次数. 然后肯定 ...

  4. linux mint 安装微信2

    很多小伙伴都用ubuntu或者Linux Mint,但由于已经习惯了让人成瘾的国产软件,比如迅雷,qq,微信等,其实我们应该培养更为健康的上网习惯,这些软件不是非用不可,但如果你不用不行, 那么也是有 ...

  5. vscode 头部注释插件

    1.安装 在vs商店搜索koroFileHeader 2.进入vscode的设置里边搜索fileheader.customMade 3.修改配置信息 "fileheader.customMa ...

  6. Java基础——2 操作符

  7. python部署到服务器(1) 一一 搭建环境

    本机环境说明 linux下的CentOS 7, 自带python2.7.5, 使用 python --version 命令查看,因系统需要python2.7.5,因此我们并不卸载,另外安装python ...

  8. CentOS 7自动以root身份登录GNOME桌面

    CentOS 7自动以root身份登录GNOME桌面 修改配置文件 /etc/gdm/custom.conf,在 [daemon] 下面添加一下两行 AutomaticLoginEnable=true ...

  9. Bmake

    Bmake is a common makefile framework. Both support native build and cross build. Easy for use, modif ...

  10. Delphi RS-232C标准