Skip to content

Commit

Permalink
feat: computed增加eager,支持立即计算出值
Browse files Browse the repository at this point in the history
  • Loading branch information
agileago committed Feb 25, 2022
1 parent 9b01358 commit 508b1c0
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 17 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,6 @@ module.exports = {
],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'off',
'no-empty': 'warn',
},
}
18 changes: 8 additions & 10 deletions example/main.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import '@abraham/reflection'
import {
Component,
Computed,
getCurrentInjector,
Hook,
Mut,
VueComponent,
VueService,
} from 'vue3-oop'
Expand All @@ -26,20 +27,17 @@ class App extends VueComponent {

outService = new OutService()

@Hook('Mounted')
mount() {
console.log(
this.injector,
this.outService.injector,
this.injector === this.outService.injector
)
}
@Mut() count = 1

@Computed('pre')
get abc() {
return this.count > 10
}
render() {
return (
<div>
<div>
指令:
指令:abc大于20:{String(this.abc)}
<input type="text" v-focus />
</div>
</div>
Expand Down
42 changes: 35 additions & 7 deletions src/decorators/computed.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,55 @@
import { computed } from 'vue'
import type { WatchOptionsBase } from 'vue'
import { computed, shallowRef, watchEffect } from 'vue'
import type { Hanlder } from '../type'
import { createDecorator, getProtoMetadata } from './util'

export const Computed: ComputedDecorator = createDecorator('Computed')

type EagerType = true | WatchOptionsBase['flush']

export interface ComputedDecorator {
(): MethodDecorator
/**
* @param eager 是否是急切的获取值
*/
(eager?: EagerType): MethodDecorator
/**
* @param shallow 是否是浅层响应式
*/
MetadataKey: string | symbol
}

function handler(targetThis: Record<any, any>) {
const list = getProtoMetadata(targetThis, Computed.MetadataKey, true)
const list = getProtoMetadata<EagerType>(
targetThis,
Computed.MetadataKey,
true
)
if (!list || !list.length) return
for (const item of list) {
const desc = item.desc
const option = item.options
if (!desc) continue
const keyVal = computed({
get: () => desc.get?.call(targetThis),
set: (v: any) => desc.set?.call(targetThis, v),
})
let keyVal: any
if (option) {
// eager computed
keyVal = shallowRef()
watchEffect(
() => {
try {
keyVal.value = desc.get?.call(targetThis)
} finally {
}
},
{
flush: option === true ? 'sync' : option,
}
)
} else {
keyVal = computed({
get: () => desc.get?.call(targetThis),
set: (v: any) => desc.set?.call(targetThis, v),
})
}
Object.defineProperty(targetThis, item.key, {
enumerable: desc?.enumerable,
configurable: true,
Expand Down

0 comments on commit 508b1c0

Please sign in to comment.