feat: oldValue for directives

This commit is contained in:
Evan You 2018-09-25 20:37:46 -04:00
parent e190824812
commit 1def00e96e

View File

@ -4,6 +4,7 @@ import { MountedComponent } from '../component'
export interface DirectiveBinding { export interface DirectiveBinding {
instance: MountedComponent instance: MountedComponent
value?: any value?: any
oldValue?: any
arg?: string arg?: string
modifiers?: DirectiveModifiers modifiers?: DirectiveModifiers
} }
@ -26,6 +27,8 @@ export interface Directive {
export type DirectiveModifiers = Record<string, boolean> export type DirectiveModifiers = Record<string, boolean>
const valueCache = new WeakMap<Directive, WeakMap<any, any>>()
export function applyDirective( export function applyDirective(
vnode: VNode, vnode: VNode,
directive: Directive, directive: Directive,
@ -35,15 +38,27 @@ export function applyDirective(
modifiers?: DirectiveModifiers modifiers?: DirectiveModifiers
): VNode { ): VNode {
const data = vnode.data || (vnode.data = {}) const data = vnode.data || (vnode.data = {})
let valueCacheForDir = valueCache.get(directive) as WeakMap<VNode, any>
if (!valueCacheForDir) {
valueCacheForDir = new WeakMap<VNode, any>()
valueCache.set(directive, valueCacheForDir)
}
for (const key in directive) { for (const key in directive) {
const hook = directive[key as keyof Directive] const hook = directive[key as keyof Directive]
const hookKey = `vnode` + key[0].toUpperCase() + key.slice(1) const hookKey = `vnode` + key[0].toUpperCase() + key.slice(1)
const vnodeHook = (vnode: VNode, prevVNode?: VNode) => { const vnodeHook = (vnode: VNode, prevVNode?: VNode) => {
let oldValue
if (prevVNode !== void 0) {
oldValue = valueCacheForDir.get(prevVNode)
valueCacheForDir.delete(prevVNode)
}
valueCacheForDir.set(vnode, value)
hook( hook(
vnode.el, vnode.el,
{ {
instance, instance,
value, value,
oldValue,
arg, arg,
modifiers modifiers
}, },