@@ -38,6 +38,104 @@ yarn add vue3-oop
3838
3939因为esbuild不支持装饰器的metadata属性,所以需要安装 [ vite-plugin-ts] ( https://github.com/CarterLi/vite/tree/main/packages/plugin-vue-jsx#readme ) 插件使用原始ts编译
4040
41+ ### 定义组件
42+
43+ ``` typescript jsx
44+ import { Autobind , ComponentProps , Computed , Hook , Link , Ref , VueComponent } from ' vue3-oop'
45+ import { Directive , VNodeChild , watch } from ' vue'
46+
47+ const focusDirective: Directive = {
48+ mounted(el : HTMLInputElement ) {
49+ el .focus ()
50+ },
51+ }
52+
53+ interface Foo_Props {
54+ size: ' small' | ' large'
55+ // 组件的slots
56+ slots: {
57+ item(name : string ): VNodeChild
58+ }
59+ }
60+
61+ class Foo extends VueComponent <Foo_Props > {
62+ // vue需要的运行时属性检查
63+ static defaultProps: ComponentProps <Foo_Props > = {
64+ size: String ,
65+ }
66+ // 组件需要的局部指令
67+ static directives: Record <string , Directive > = {
68+ focus: focusDirective ,
69+ }
70+ constructor () {
71+ super ()
72+ // watch在构造函数中初始化
73+ watch (
74+ () => this .count ,
75+ () => {
76+ console .log (this .count )
77+ },
78+ )
79+ }
80+
81+ // 组件自身状态
82+ @Ref () count = 1
83+ // 计算属性
84+ @Computed ()
85+ get doubleCount() {
86+ return this .count * 2
87+ }
88+ add() {
89+ this .count ++
90+ }
91+ // 自动绑定this
92+ @Autobind ()
93+ remove() {
94+ this .count --
95+ }
96+
97+ // 生命周期
98+ @Hook (' Mounted' )
99+ mount() {
100+ console .log (' mounted' )
101+ }
102+
103+ // 对元素或组件的引用
104+ @Link () element? : HTMLDivElement
105+
106+ render() {
107+ return (
108+ < div ref = " element" >
109+ <span >{this.props.size }< / span >
110+ < button onClick = {() => this.add()}> + </button >
111+ <span >{this.count }< / span >
112+ < button onClick = {this.remove }> - </button >
113+ <div >{this.context.slots.item?.(' aaa' )}</div>
114+ <input type=" text" v-focus />
115+ </div>
116+ )
117+ }
118+ }
119+
120+ ` ` `
121+
122+ ### 定义服务
123+
124+ 组件和服务的差距是缺少了render这一个表现UI的函数,其他都基本一样
125+
126+ ` ` ` typescript
127+ class CountService extends VueService {
128+ @Ref() count = 1
129+ add() {
130+ this.count++
131+ }
132+ remove() {
133+ this.count--
134+ }
135+ }
136+ ` ` `
137+
138+
41139### 依赖注入
42140
43141Angular文档
@@ -47,3 +145,25 @@ Angular文档
47145- [服务与依赖注入简介](https://angular.cn/guide/architecture-services)
48146- [多级注入器](https://angular.cn/guide/hierarchical-dependency-injection)
49147- [依赖注入实战](https://angular.cn/guide/dependency-injection-in-action)
148+
149+ ` ` ` typescript jsx
150+ import { VueComponent, VueService } from ' vue3-oop'
151+ import { Injectable } from ' injection-js'
152+
153+ // 组件DI
154+ @Component({
155+ providers: [CountService ]
156+ })
157+ class Bar extends VueComponent {
158+ constructor (private countService : CountService ) {super ()}
159+
160+ render() {
161+ return <div >{this.countService.count }< / div >
162+ }
163+ }
164+
165+ @Injectable ()
166+ class BarService extends VueService {
167+ constructor (private countService : CountService ) {super ()}
168+ }
169+ ` ` `
0 commit comments