深入使用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全家桶能够掌握和运用 此次项目模版主要涉 ...
随机推荐
- jq之display:none与visible:hidden
http://www.cnblogs.com/linxiong945/p/4075146.html 今天学习到jquery的hide()部分时,突然有一个想法,jquery中的隐藏/显示部分的实现是给 ...
- 进阶Java编程(7)反射机制
反射机制 1,反射机制简介 在Java语言里面之所以会有如此多的开源技术支撑,很大的一部分是来自于Java最大的特征[反射机制].如果你不能够使用反射机制去进行项目的开发与设计,那么可以说你并未接触到 ...
- 05 正确运行一个Go程序
Go代码文件,程序中必须指定启动函数main() Hello.go package main //声明为main包,即可以编译成二进制程序 import "fmt" //导入fmt ...
- django 中间键重定向
1,定义和注册中间件 在注册的中间件中使用: from django.http import HttpResponseRedirect '''下面的书写方法会陷入死循环,所以必须加判断条件只调用一次' ...
- vue报错Maximum call stack size exceeded at abort (webpack-internal:///./node_modules/_vue-router@3.1.3@vue-router/dist/vue-router.esm.js:2079)
报错原因: import cellDetail from '@/components/common/dialog/cellDetail.vue'; 解决方法: import celldetail fr ...
- 6.声明式异常处理、I18N
声明式异常处理 1.在Action 中进行异常映射 <exception-mapping result="error" exception="java.sql.SQ ...
- Python脚本带-的参数脚本
一.故事背景 由于先前的工作内容是做后台开发,对于脚本写的很少: 昨天参加面试遇到一道面试题,写一个python脚本: 通过脚本的后面的参数选项获取参数选项后面的字符串进行处理: 问题没记错的话大概是 ...
- linux下共享热点抓包
Linux有一个抓包工具叫tcpdump,这个命令还是挺强大的.简单列举一下它的参数 # tcpdump -h tcpdump version 4.9.2 libpcap version 1.8.1 ...
- js数组的所有方法
修改器方法 下面的这些方法会改变调用它们的对象自身的值: Array.prototype.copyWithin() 在数组内部,将一段元素序列拷贝到另一段元素序列上,覆盖原有的值. Array.pr ...
- 静态static最基础的知识
static静态: 常见修饰的内容: 1.变量: 修饰变量时,叫静态变量或类变量.此变量为类所有随着虚拟机加载类是而加载入方法区,此静态变量为该类所有对象共享,在内存中只有一个副本,它 当且仅当 类的 ...