深入使用Vue + TS
深入使用TS
支持 render jsx 写法
这里一共分两步
首先得先让
vue支持jsx写法再让
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单文件中的ts写jsx代码了,如下图所示:
敲黑板,这里又有重点,使用
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的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- 【vue&ts开发】Vue 3.0前的 TypeScript 最佳入门实践
1.使用官方脚手架构建 新的 VueCLI工具允许开发者 使用 TypeScript 集成环境 创建新项目. 只需运行 vue createmy-app. 然后,命令行会要求选择预设.使用箭头键选择 ...
- vue + ts Vuex篇
Vuex对Typescript的支持,仍十分薄弱,官方库只是添加了一些.d.ts声明文件,并没有像vue 2.5这样内置支持. 第三方衍生库 vuex-typescript, vuex-ts-deco ...
- vue+ts搭建项目
Tip: 为了避免浪费您的时间,本文符合满足以下条件的同学借鉴参考 1.本文模版不适用于小型项目,两三个页面的也没必要用vue2.对typescript.vue全家桶能够掌握和运用 此次项目模版主要涉 ...
随机推荐
- 简单了解soap协议
SOAP的是什么的简写 soap是(Simple Object Access Protocal)的简写,即简单对象访问协议,它描述了一种在分散或分布式的环境中如何交换信息的轻量级协议. soap用来干 ...
- PHP获取某段文字作为标题
<?php mb_internal_encoding('utf-8'); // 提取文字标题,多余文字用省略号替换 $arr=[ '用心用情用功,进行无愧于时代的文艺创造', '一图了解第二届一 ...
- 在vue-cli项目中使用bootstrap
1.安装插件 npm install jquery --save npm install bootstrap --save npm install popper.js --save 2.配置webpa ...
- netty的断线重连问题
手里的这个项目需要作为客户端,不断的接收服务端发来的数据,用的netty框架,但是一直存在一个问题,就是断线重连问题. 什么是断线重连呢? 就是我们这个客户端要保证一直与服务端保持连接,这样客户端才能 ...
- axiso基本使用及python接收处理
安装$ npm install axios 1.发送get请求: axios.get("/api/v1.0/cars?id=132").then(function(res){ co ...
- 【Day1】4.基础语法及分支结构
视频地址(全部) https://edu.csdn.net/course/detail/26057 课件地址(全部) https://download.csdn.net/download/gentl ...
- Android 计算器制作 2.注册View 构建函数
鄙人新手 整了 快两天 终于搞定了.. 1.首先是MainActivity 中 在Oncreate函数中 注册 2.按+ 或者 - 号 来分成两大字符串 s1 和 s2 再将s2 分为更小的s1 和 ...
- vim文本编辑及文件查找应用1
vim编辑器: 文本编辑器: 文本:纯文本,ASCII text;Unicode(全球通用); 文本编辑种类: 行编辑器:sed 全屏编辑器:nano, ...
- RabbitMQ各种交换机类型Exchange Types介绍
最新版本的RabbitMQ有四种交换机类型,分别是Direct exchange.Fanout exchange.Topic exchange.Headers exchange. 一.Direct E ...
- sql 实现取表中相同id时间最大的一行 利用distinct on
数据表是这样的 select * from water_level_records m where ( select count(*) from water_level_records n where ...