Skip to content

xxbld/awesome-vue-tsx

Repository files navigation

使用vue (cli3) + tsx的一些总结

喜欢ts,打死也要用vue+tsx

创建一个ts项目

vue create

  • 必选: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');
  }
}

vue常见的ts使用方法

创建带提示的tsx组件

常用组件tsx提示包装

使用ts|tsx需要注意的事项

class 写法

  1. 属性声明
  • 非响应式属性在created中初始化,不建议使用constructor构造函数
  • 禁止使用dataget 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';
    }

}
  1. render函数写法 参考
  • 编译目标环境为es5时需要手动注入h
  • 当使用保留字做props如:v+驼峰命名、style时需要注意jsx组件的写法
  • 直接在组件上使用v+驼峰命名props会被当做vue指令编译
  • 直接在组件上使用styleprops会被当做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>);
    }
}