vue3-core/packages/runtime-core/src/compat/customDirective.ts

50 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-04-07 00:17:17 +08:00
import { isArray } from '@vue/shared'
2021-04-06 23:57:10 +08:00
import { ObjectDirective, DirectiveHook } from '../directives'
import { softAssertCompatEnabled } from './compatConfig'
import { DeprecationTypes } from './deprecations'
2021-04-06 23:57:10 +08:00
export interface LegacyDirective {
bind?: DirectiveHook
inserted?: DirectiveHook
update?: DirectiveHook
componentUpdated?: DirectiveHook
unbind?: DirectiveHook
}
const legacyDirectiveHookMap: Partial<
Record<
keyof ObjectDirective,
keyof LegacyDirective | (keyof LegacyDirective)[]
>
> = {
beforeMount: 'bind',
mounted: 'inserted',
updated: ['update', 'componentUpdated'],
unmounted: 'unbind'
}
export function mapCompatDirectiveHook(
name: keyof ObjectDirective,
dir: ObjectDirective & LegacyDirective
): DirectiveHook | DirectiveHook[] | undefined {
const mappedName = legacyDirectiveHookMap[name]
if (mappedName) {
if (isArray(mappedName)) {
const hook: DirectiveHook[] = []
mappedName.forEach(name => {
const mappedHook = dir[name]
if (mappedHook) {
softAssertCompatEnabled(DeprecationTypes.CUSTOM_DIR, mappedName, name)
2021-04-06 23:57:10 +08:00
hook.push(mappedHook)
}
})
return hook.length ? hook : undefined
} else {
if (dir[mappedName]) {
softAssertCompatEnabled(DeprecationTypes.CUSTOM_DIR, mappedName, name)
2021-04-06 23:57:10 +08:00
}
return dir[mappedName]
}
}
}