喜欢ts,打死也要用vue+tsx
- 必选:babel,ts
- 推荐:node-sass,eslint+prettier
- 可选:vuex,router
vue cli 并没直接支持jsx/tsx的热更新(SFC默认支持热更新),需要引入插件
module.exports = {
publicPath: './',
lintOnSave: false,
chainWebpack: config => {
// JSX|TSX 热更新
config.module
.rule(/\.(j|t)sx$/)
.test(/\.(j|t)sx$/)
.use('vue-jsx-hot-loader')
.before('babel-loader')
.loader('vue-jsx-hot-loader');
}
}
常用组件tsx提示包装
- 属性声明
- 非响应式属性在
created
中初始化,不建议使用constructor
构造函数 - 禁止使用
data
或get data
作为组件响应式属性
@Component
export default class Test extends Vue {
attr0 = true; // reactive
attr1:string; // not reactive
// forbid
// 原因:编译时会被当成{data(){return {}}}
// data = 'data';
// get data(){return this.attr0}
// 可以使用但不建议
// @Prop()data!:string[];
// @Prop()style!:string;
// @Prop()vTest!:string; //v开头的驼峰命名属性
//constructor(){super()} //not recommend
// recommend
created(){
this.attr1 = 'test';
}
}
- render函数写法 参考
- 编译目标环境为es5时需要手动注入
h
- 当使用保留字做
props
如:v+驼峰命名、style时需要注意jsx组件的写法 - 直接在组件上使用
v+驼峰命名
的props
会被当做vue指令编译 - 直接在组件上使用
style
的props
会被当做html style
编译
@Component
export default class Test extends Vue {
// render(h:any){} // right also
render(){
// NOTICE: ES6以上又会自动注入h,此时下面这句编译时会报错
const h = this.$createElement;
// const jsxError = (<Comp style={} vTest={}/>);
const jsxCorrect=(<Com {...{props:{style:{},vTest:{}}}}/>);
return (
<div>
{/**{jsxError}*/}
{jsxCorrect}
</div>);
}
}