1 Star 6 Fork 0

编码猿 / VueClassApiTsx

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

前言:

前端发展真的是一个轮回,越发展越偏向原生Vue3开发阶段就参与并使用了,但是Vue3真的垃圾,十分的不喜欢这种垃圾的语法,钟爱classts装饰器,所以有了本项目!!

本项目作为Vue脚手架而存在,已在很多公司项目中落地并经过不断打磨,同时为了更优雅的代码开发,本人写了很多周边的辅助插件,装饰器,shell,为你提供类似java开发中SpringBoot那般优雅的爽快感!

围绕项目开发的插件有:

1: vue-cli-plugin-tsx-autorouter tsx自动路由插件 受Nuxt.js的思想启发,针对本项目tsx开发,根据页面结构自动生成路由配置文件,借助babelast实现提取tsx中类的属性进而实现路由meta

2:./bin/tinit 封装shell命令行工具,实现通过命令行直接创建众多代码文件

3:解耦前端 页面 & JSON数据,实现JSON映射存储到类属性:

4:装饰器(将封装成通用TS项目插件):

  • 1: 让代码更加优雅简洁高效的请求中间层装饰器 @GET,@POST,@DELETE,@PUT
       @GET()
       @Mapper(ResponseType)
       public async IndexTest (params: object): Promise<ResponseType[]> {
           // 留空,不要写请求代码 即可发送请求,除非 useHandle: true,这时 方法入参  params 为 ajax 接口数据,直接处理 params
           // 即可,同时也不需要写请求代码!!
       }
  • 2: 依赖注入装饰器:@Autowired
  • 3: 其他装饰器:@GlobalMethod,@Mapper,@RegVuePlugs,@RegServiceAndMethods,@Start 等等..

5:AutoServiceCodeGeneration:实时监听configure.config.ts配置文件,然后根据ApiList中的对象key名称自动生成请求中间层的代码,降低手动复制的低效率! 介绍: 1: 文件监听:已通过Nodejs流操作实现文件监听,读取,提取,核心代码,并实现同一文件中不同编辑下的新旧数据Diff。 2:请求中间层代码自动生成:思路已有,挑战性不足,所以还未进行代码实现

TsxVueClassApi

基于Vue Class ApiTypeScriptJSX,搭建的一套项目脚手架,实现了很多常用的注解,同时基于babel插件通过Ast语法树进行路由配置文件的自动生成等。

如果你喜欢JSX,那么这套脚手架你应该会十分喜欢,代码语法如下:

import "@pageLess/Home.less";
import { Component } from 'vue-property-decorator';
import HelloWorld from '@components/HelloWorld';
import { HomeLogic } from "@logic/page/Home.logic";
import { Getter } from "vuex-class";
import { IndexUtils } from "@utils/index.utils";
import { Autowired } from "@ann/Ioc.annotation";
import { VueCustomize, RouterMeta } from "@logic/Base.type";

@Component
export default class Home extends VueCustomize {
  // RouterMeta 是 vue-router 路由meta配置信息,会被 我们的插件
  // vue-cli-plugin-tsx-autorouter 进行 ast 提取注入到 自动生成的 路由配置文件中
  public RouterMeta: RouterMeta = {
    title: '首页',
    showNav: true,
    isLogin: true
  }

  // 抽离组件所有逻辑到独立类,解耦 页面层 和 逻辑层
  // 通过 Autowired 依赖注入装饰器 实现 注入 逻辑 -> 页面
  // 同时 传入 vue 的 this,实现逻辑层可以调用vue方法
  @Autowired(Home)
  private logic!: HomeLogic<Home>

  @Autowired()
  public readonly Utils!: IndexUtils;

  @Getter('GettersTabsContentArr')
  public readonly getterFoo!: Array<any>;

  public async created() {
    await this.logic.StartUp();
  }

  public ClickButton(): JSX.Element {
    return (
      <a-button type="primary" onClick={async () => {
        console.log("按钮被点击22222");
      }}>
        Primary
      </a-button>
    )
  }

  public back() {
    console.log("qqqq");
  }

  protected render() {
    return (
      <div class="home">
        <img src="/img/baidu.png" alt="" />
        <h1 on-click={this.back}>111</h1>
        <HelloWorld msg="向HelloWorld props传参" />
        <input type="text" v-model={this.logic.title} />
        <h2>{this.logic.title}</h2>
        {this.ClickButton()}
        <ul>
          {
            this.logic.List.map(v => {
              return <li>
                {v.user_id}
                {v.user_name}
              </li>
            })
          }
        </ul>
      </div>
    )
  }
}

这个脚手架我们正在项目中使用,同时也在不断的开发和完善!!!!

1:安装

需要额外全局安装的插件有:

npm i -g concurrently cross-env gulp

然后下载项目,初始化并启动:

git clone https://gitee.com/bmycode/vue-class-api-tsx.git
npm i
npm run start
# 注意!!!:网站运行后使用电脑本机的局域网ip地址来访问,例如:http://192.168.1.101:8080/#/Home

注意

Vue官方原生底层就支持JSX语法,但是官方没有关于Vue中使用JSX的文档,而且很多Vueui框架和第三方插件都没有相关语法,但是这不影响我们在Vue中正常使用JSX。很多语法需要特殊注意和改造一下!!

2:使用

下面说下这个脚手架的使用和注意事项。

2.1:项目结构

请仔细看文件后面的中文说明!!!

├── README.md
├── babel.config.js babel配置文件
├── bin   终端NewFile工具
│   ├── config 
│   │   └── index.js
│   └── tinit
├── dist  打包后的文件夹
├── gulpfile.js  gulp配置文件,实现监听page自动生成路由文件
├── package.json 核心依赖配置文件
├── public       公共的资源文件
├── src          存放核心源码
│   ├── application  页面相关
│   │   ├── app.tsx 最外层顶级父组件
│   │   ├── assets  静态资源回合webpack打包进源码
│   │   ├── components 公共组件
│   │   ├── logic      【重要】TSX组件中的js逻辑抽象层
│   │   │   ├── base.logic.ts  【重要】所有TSX组件的js逻辑父类
│   │   │   ├── base.type.ts 组件中 通用类型的编写
│   │   │   └── page   【重要】对应页面的TSX组件逻辑抽象
│   │   └── page  【重要】存放TSX页面组件
│   └── core  核心JS层
│       ├── annotation 存放自己开发的装饰器
        │   ├── JsonToClass json-mapper-class 的源代码
│       │   ├── http.annotation.ts  请求装饰器
│       │   ├── ioc.annotation.ts   IOC依赖装饰器
│       │   └── register.annotation.ts 启动装饰器
│       ├── config    站点配置文件
│       │   ├── configure.config.ts 核心配置文件
│       │   └── route.config.ts     自动生成的路由配置文件
│       ├── dao                     axios的封装
│       ├── model                   TS存取器
│       ├── run                     项目的启动类
│       │   ├── init.run.ts   初始化Vue各种配置
│       ├── service           请求的service层封装
│       │   └── impl          请求service的具体类
│       ├── store             Vuex的配置
│       ├── types             自定义的声明文件
│       └── utils             工具函数
├── tsconfig.json             TS的配置文件
└── vue.config.js             Vue-cli3 的配合文件

2.2:编码注意事项和规范,严格遵守!!!

1:page/文件夹中的所有tsx组件必须继承自VueCustomizeVueCustomize是所有页面的父类,可以在这里定义一些公共的类型!

2:logic/文件夹中的所有logic.ts必须继承BaseLogic并实现接口MethodsBaseLogic是所有页面逻辑层的公共封装,可以把使用率高的接口或者变量放在BaseLogic 中去定义和实现,这样页面的逻辑层子类可以实现直接使用!

3:logic/中页面的逻辑层可以使用装饰器@Autowired()去注入多个service的依赖,实现对ajax中间层方法的调用,以发送ajax请求!具体的看下面代码

import { Autowired } from "@/core/annotation/Ioc.annotation";
import { UserServiceImpl, ResponseType} from "@/core/service/impl/User.service.impl";
import { BaseLogic } from "@logic/Base.logic";
import { Methods, VueCustomize } from "@logic/Base.type";

export class HomeLogic<T extends VueCustomize> extends BaseLogic implements Methods {

  @Autowired()
  public readonly UserServiceImpl!: UserServiceImpl;

  public title: string = "12222";
  
  public List: ResponseType[] = [];

  constructor(_: T) {
    super();
    this._ = _
  }

  /**
   * 在这里面调用需要打开页面就执行的ajax请求
   * @constructor
   */
  public async StartUp (): Promise<void> {
    await this.getData();
  }

  /**
   * 请求首页数据
   */
  public async getData (): Promise<void> {
    this.List = await this.UserServiceImpl.IndexTest({ type: 1, page: 1 });
    console.log("this.List: ", this.List);


    // let res = await this.UserServiceImpl.login({ type: 2, page: 2 });
    // console.log("this.res: ", res);
    
    // this._.$setToken("")
    // await this._.$router.push('/About')
  }
}

4:logic/中必须实现构造函数constructor,在构造函数中保存tsx页面传入指向vue实例的this,这样才能在logic中正确使用vue的一些方法,具体看代码:

constructor(_: T) {
  super();
  this._ = _
}

/**
 * 请求首页数据
 */
public async getData (): Promise<void> {
  this.List = await this.UserServiceImpl.IndexTest({ type: 1, page: 1 });
  console.log("this.List: ", this.List);
}

5:如何将自定义的方法通过 Vue.prototype.xxx 挂载到Vue上以方便全局使用?

答:在utils/index.utils.ts中定义方法的时候请使用装饰器@GlobalMethod()装饰方法,然后如果你在tsx页面组件中需要使用此方法,那么请在base.type.ts中定义变量并编写变量类型!

同时如果你需要在logic逻辑层使用此方法,那么需要在base.logic.tsVueType接口中编写类型。具体请看代码:

// src/core/utils/index.utils.ts

import { ConfigureConfig } from "@config/configure.config";
import { GlobalMethod } from "@ann/Register.annotation";

export class IndexUtils {
  /**
   * 方法上打上 @GlobalMethod() 注解,这个方法会自动成为vue的全局方法
   * 组件中直接:this.$setToken() 即可
   */
  @GlobalMethod()
  public setToken (args: string): void {
    localStorage.setItem("token", args)
  }
}

// src/application/logic/base.logic.ts

// 定义 $setToken 方法和入参类型,返回值等!
export class VueCustomize extends Vue {
  $setToken!: (token: string) => void
}

如果你觉得上面方式使用全局方法太过于麻烦,那么你可以在你需要使用的logic类或tsx组件中使用装饰器@Autowired()来注入index.utils.ts到类属性中,代码示例:

import "@pageLess/Home.less";
import { Component } from 'vue-property-decorator';
import HelloWorld from '@components/HelloWorld';
import { HomeLogic } from "@logic/page/Home.logic";
import { Getter } from "vuex-class";
// 1:导入需要被注入的类
import { IndexUtils } from "@utils/index.utils";
// 2:导入装饰器
import { Autowired } from "@ann/Ioc.annotation";
import { VueCustomize, RouterMeta } from "@logic/Base.type";
import { toClass, toInterface, configFilePath } from "json-class-interface";
@Component
export default class Home extends VueCustomize {

  // 抽离组件所有逻辑到独立类,解耦页面和数据
  @Autowired(Home)
  private logic!: HomeLogic<Home>

  // RouterMeta 是 vue-router 路由meta配置信息,会被ast提取注入到自动生成的路由配置文件中
  public RouterMeta: RouterMeta = {
    title: '首页',
    showNav: true,
    isLogin: true
  }

  // 3:将 IndexUtils 注入到属性 Utils 中
  @Autowired()
  public readonly Utils!: IndexUtils;

  @Getter('GettersTabsContentArr')
  public readonly getterFoo!: Array<any>;


  public async created () {
    // 4:使用 setToken 方法
    this.Utils.setToken("1111")
  }



  public ClickButton(): JSX.Element {
    return (
      <a-button type="primary" onClick={async () => {
        console.log("按钮被点击22222");
      }}>
        Primary
      </a-button>
    )
  }

  public back() {
    console.log("qqqq");
  }


  protected render() {
    return (
      <div class="home">
        <img src="/img/baidu.png" alt="" />
        <h1 on-click={this.back}>111</h1>
        <HelloWorld msg="向HelloWorld props传参" />
        <input type="text" v-model={this.logic.title} />
        <h2>{this.logic.title}</h2>
        {this.ClickButton()}
        <ul>
          {
            this.logic.List.map(v => {
              return <li>
                {v.user_id}
                {v.user_name}
                </li>
            })
          }
        </ul>
      </div>
    )
  }
}

2.3:使用注意事项

1: 项目中的路由使用的是vue-router,同时我借鉴了Nuxt.js的思想,自己开发了路由配置文件自动生成的插件,这个插件是Vue-cli 3的插件,所以不能在Vue cli 2的项目中使用!!

插件源码已经提交npm包市场!请完整阅读下面的插件文档,路由的配置文件让插件帮我们自动生成就好了!!!

vue-cli-plugin-tsx-autorouter

2: 同时借鉴PHP开发框架Laravel开发终端命令行工具,通过命令帮我们创建带有模板代码能直接运行的文件!代码放在 bin/ 文件夹中!

使用手册:

╭─bmy@MacBook-Pro /Applications/Source/TsxVueClassApi ‹master*
╰─$ ./bin/tinit -h
Usage: tinit [options]

Options:
  -t, --file-type <type>  文件类型: [page,logic,service,impl,less]
  -n, --file-name <name>  被创建的文件名称
  -i, --is-create <is>    是否为 -t 参数自动创建相关文件类型 (default: false)
  -v, --version           显示当前的版本
  -h, --help              display help for command

参数说明:

  • -t:需要被创建的文件类型,取值 page(TSX页面),logic(TSX页面的js抽象层),service(请求中间层的接口),impl(实现接口的类),less(css样式文件)。可以多传!
  • -n:需要被创建的文件名
  • -i:如果数值为true,那么会自动创建 -t 参数所有的文件类型

使用案例:

╭─bmy@MacBook-Pro /Applications/Source/TsxVueClassApi ‹master*
╰─$ ./bin/tinit -t page logic -n Test
成功创建文件...

上面命令执行后会分别在src/application/page中创建创建文件Text.tsx页面组件,同时在src/application/logic/page中创建Test.logic.ts的逻辑层文件。

多试几次,请自行熟练掌握!!

3:开发中功能

  • 【重要】1:实现ajax请求到的数据和model层的映射绑定,这种数据绑定关系,可以完全解决后端改接口字段从而导致前端代码也需要同步大量修改的问题!!

  • 【不太重要】1:实时监听configure.config.ts配置文件,然后根据ApiList中的对象key名称自动在service层的类中生成对应的方法,降低手动复制的低效率!

    • 已实现功能,但未整合进项目!
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

基于Vue Class Api 语法 和 TSX 开发的一套项目脚手架,同时使用babel AST语法树提取代码实现自动路由配置生成等 展开 收起
TypeScript 等 4 种语言
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
TypeScript
1
https://gitee.com/bmycode/vue-class-api-tsx.git
git@gitee.com:bmycode/vue-class-api-tsx.git
bmycode
vue-class-api-tsx
VueClassApiTsx
master

搜索帮助