-
Notifications
You must be signed in to change notification settings - Fork 343
/
lifecycle.ts
49 lines (45 loc) · 1.63 KB
/
lifecycle.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { VueConstructor } from 'vue'
import { ComponentInstance } from '../component'
import { getCurrentVue, setCurrentVM, getCurrentVM } from '../runtimeContext'
import { currentVMInFn } from '../helper'
const genName = (name: string) => `on${name[0].toUpperCase() + name.slice(1)}`
function createLifeCycle(lifeCyclehook: string) {
return (callback: Function) => {
const vm = currentVMInFn(genName(lifeCyclehook))
if (vm) {
injectHookOption(getCurrentVue(), vm, lifeCyclehook, callback)
}
}
}
function injectHookOption(
Vue: VueConstructor,
vm: ComponentInstance,
hook: string,
val: Function
) {
const options = vm.$options as any
const mergeFn = Vue.config.optionMergeStrategies[hook]
options[hook] = mergeFn(options[hook], wrapHookCall(vm, val))
}
function wrapHookCall(vm: ComponentInstance, fn: Function) {
return (...args: any) => {
let preVm = getCurrentVM()
setCurrentVM(vm)
try {
return fn(...args)
} finally {
setCurrentVM(preVm)
}
}
}
// export const onCreated = createLifeCycle('created');
export const onBeforeMount = createLifeCycle('beforeMount')
export const onMounted = createLifeCycle('mounted')
export const onBeforeUpdate = createLifeCycle('beforeUpdate')
export const onUpdated = createLifeCycle('updated')
export const onBeforeUnmount = createLifeCycle('beforeDestroy')
export const onUnmounted = createLifeCycle('destroyed')
export const onErrorCaptured = createLifeCycle('errorCaptured')
export const onActivated = createLifeCycle('activated')
export const onDeactivated = createLifeCycle('deactivated')
export const onServerPrefetch = createLifeCycle('serverPrefetch')