Skip to content

v-on 的支持

重构

在继续实现之前,让我们进行一些重构.
目前,在 codegen 生成的代码中,我们从 sharedruntime-core 导入(或解构)了许多辅助函数.
而且在 codegen(和 transform)的实现中,我们硬编码了函数名称.这不是很明智.

这次,让我们将它们重构为 runtime-helper 并用符号集中管理,进一步地,更改实现以仅导入必要的内容.

首先,让我们在 compiler-core/runtimeHelpers.ts 中实现表示每个辅助函数的符号.
到目前为止,我们一直使用 h 函数来生成 VNode,但这次,让我们按照原始实现更改为使用 createVNode
runtime-core/vnode 导出 createVNode,并在 genVNodeCall 中,更改代码以调用 createVNode 而不是 genVNodeCall

ts
export const CREATE_VNODE = Symbol()
export const MERGE_PROPS = Symbol()
export const NORMALIZE_CLASS = Symbol()
export const NORMALIZE_STYLE = Symbol()
export const NORMALIZE_PROPS = Symbol()

export const helperNameMap: Record<symbol, string> = {
  [CREATE_VNODE]: 'createVNode',
  [MERGE_PROPS]: 'mergeProps',
  [NORMALIZE_CLASS]: 'normalizeClass',
  [NORMALIZE_STYLE]: 'normalizeStyle',
  [NORMALIZE_PROPS]: 'normalizeProps',
}

使符号在 CallExpression 中可用作 callee

ts
export interface CallExpression extends Node {
  type: NodeTypes.JS_CALL_EXPRESSION
  callee: string | symbol
}

TransformContext 中实现一个区域来注册辅助函数和注册它们的函数.

ts
export interface TransformContext extends Required<TransformOptions> {
  currentNode: RootNode | TemplateChildNode | null
  parent: ParentNode | null
  childIndex: number
  helpers: Map<symbol, number> // 这个
  helper<T extends symbol>(name: T): T // 这个
}

export function createTransformContext(
  root: RootNode,
  { nodeTransforms = [], directiveTransforms = {} }: TransformOptions,
): TransformContext {
  const context: TransformContext = {
    // .
    // .
    // .
    helpers: new Map(),
    helper(name) {
      const count = context.helpers.get(name) || 0
      context.helpers.set(name, count + 1)
      return name
    },
  }

  return context
}

用这个辅助函数替换硬编码的部分,并修改 Preamble 以使用注册的辅助函数.

ts
// 示例)
propsExpression = createCallExpression('mergeProps', mergeArgs, elementLoc)
// ↓
propsExpression = createCallExpression(
  context.helper(MERGE_PROPS),
  mergeArgs,
  elementLoc,
)

context 传递给 createVNodeCall 并在其中注册 CREATE_VNODE

ts
export function createVNodeCall(
  context: TransformContext | null, // 这个
  tag: VNodeCall['tag'],
  props?: VNodeCall['props'],
  children?: VNodeCall['children'],
  loc: SourceLocation = locStub,
): VNodeCall {
  // 这里 ------------------------
  if (context) {
    context.helper(CREATE_VNODE)
  }
  // ------------------------

  return {
    type: NodeTypes.VNODE_CALL,
    tag,
    props,
    children,
    loc,
  }
}
ts
function genVNodeCall(
  node: VNodeCall,
  context: CodegenContext,
  option: Required<CompilerOptions>,
) {
  const { push, helper } = context
  const { tag, props, children } = node

  push(helper(CREATE_VNODE) + `(`, node) // 调用 createVNode
  genNodeList(genNullableArgs([tag, props, children]), context, option)
  push(`)`)
}
ts
export function transform(root: RootNode, options: TransformOptions) {
  const context = createTransformContext(root, options)
  traverseNode(root, context)
  root.helpers = new Set([...context.helpers.keys()]) // 将辅助函数添加到 root
}
ts
// 根据原始实现添加 `_` 作为前缀来为其设置别名
const aliasHelper = (s: symbol) => `${helperNameMap[s]}: _${helperNameMap[s]}`

function genFunctionPreamble(ast: RootNode, context: CodegenContext) {
  const { push, newline, runtimeGlobalName } = context

  // 基于在 ast 中注册的辅助函数生成辅助函数声明
  const helpers = Array.from(ast.helpers)
  push(
    `const { ${helpers.map(aliasHelper).join(', ')} } = ${runtimeGlobalName}\n`,
  )
  newline()
}
ts
// 在 genCallExpression 中处理符号并将它们转换为辅助函数调用。

export interface CodegenContext {
  // .
  // .
  // .
  helper(key: symbol): string
}

function createCodegenContext(ast: RootNode): CodegenContext {
  const context: CodegenContext = {
    // .
    // .
    // .
    helper(key) {
      return `_${helperNameMap[key]}`
    },
  }
  // .
  // .
  // .
  return context
}

// .
// .
// .

function genCallExpression(
  node: CallExpression,
  context: CodegenContext,
  option: Required<CompilerOptions>,
) {
  const { push, helper } = context

  // 如果是符号,从辅助函数中获取它
  const callee = isString(node.callee) ? node.callee : helper(node.callee)

  push(callee + `(`, node)
  genNodeList(node.arguments, context, option)
  push(`)`)
}

通过这样,我们这次进行的重构就完成了.我们能够清理硬编码的部分!

编译结果

※ 注意

  • 输入使用的是前一个游乐场的输入
  • 实际上在 function 前面有一个 return
  • 生成的代码用 prettier 格式化

当你这样看时,有太多不必要的换行和空格...

好吧,让我们在其他地方改进这个.

ts
function render(_ctx) {
  with (_ctx) {
    const {
      normalizeProps: _normalizeProps,
      createVNode: _createVNode,
      normalizeClass: _normalizeClass,
    } = ChibiVue

    return _createVNode('div', null, [
      '\n  ',
      _createVNode('p', _normalizeProps({ id: count }), ' v-bind:id="count" '),
      '\n  ',
      _createVNode(
        'p',
        _normalizeProps({ id: count * 2 }),
        ' :id="count * 2" ',
      ),
      '\n\n  ',
      _createVNode(
        'p',
        _normalizeProps({ ['style' || '']: bind.style }),
        ' v-bind:["style"]="bind.style" ',
      ),
      '\n  ',
      _createVNode(
        'p',
        _normalizeProps({ ['style' || '']: bind.style }),
        ' :["style"]="bind.style" ',
      ),
      '\n\n  ',
      _createVNode('p', _normalizeProps(bind), ' v-bind="bind" '),
      '\n\n  ',
      _createVNode(
        'p',
        _normalizeProps({ style: { 'font-weight': 'bold' } }),
        ' :style="{ font-weight: \'bold\' }" ',
      ),
      '\n  ',
      _createVNode(
        'p',
        _normalizeProps({ style: 'font-weight: bold;' }),
        ' :style="\'font-weight: bold;\'" ',
      ),
      '\n  ',
      _createVNode(
        'p',
        _normalizeProps({
          class: _normalizeClass('my-class my-class2'),
        }),
        ' :class="\'my-class my-class2\'" ',
      ),
      '\n  ',
      _createVNode(
        'p',
        _normalizeProps({ class: _normalizeClass(['my-class']) }),
        ' :class="[\'my-class\']" ',
      ),
      '\n  ',
      _createVNode(
        'p',
        _normalizeProps({
          class: _normalizeClass({ 'my-class': true }),
        }),
        ' :class="{ \'my-class\': true }" ',
      ),
      '\n  ',
      _createVNode(
        'p',
        _normalizeProps({
          class: _normalizeClass({ 'my-class': false }),
        }),
        ' :class="{ \'my-class\': false }" ',
      ),
      '\n',
    ])
  }
}

v-on

这次要实现的开发者接口

现在让我们继续实现 v-on.

v-on 也有各种开发者接口. https://vuejs.org/guide/essentials/event-handling.html

这是我们这次的目标.

ts
import { createApp, defineComponent, ref } from 'chibivue'

const App = defineComponent({
  setup() {
    const count = ref(0)
    const increment = (e: Event) => {
      console.log(e)
      count.value++
    }
    return { count, increment, state: { increment }, eventName: 'click' }
  },

  template: `<div>
    <p>count: {{ count }}</p>

    <button v-on:click="increment">v-on:click="increment"</button>
    <button v-on:[eventName]="increment">v-on:click="increment"</button>
    <button @click="increment">@click="increment"</button>
    <button v-on="{ click: increment }">v-on="{ click: increment }"</button>

    <button @click="state.increment">v-on:click="increment"</button>
    <button @click="count++">@click="count++"</button>
    <button @click="() => count++">@click="() => count++"</button>
    <button @click="increment($event)">@click="increment($event)"</button>
    <button @click="e => increment(e)">@click="e => increment(e)"</button>
</div>`,
})

const app = createApp(App)

app.mount('#app')

我想要做的事情

实际上,关于解析器的实现,前一章的实现就足够了,问题在于转换器的实现. 转换的内容主要根据 arg 的存在与否和 exp 的类型而变化. 当没有 arg 时,需要做的事情几乎与 v-bind 相同.

换句话说,需要考虑的是可以作为 arg 的 exp 类型以及为它们转换必要的 AST Node.

  • 任务 1 分配一个函数. 这是最简单的情况.

    html
    <button v-on:click="increment">increment</button>
  • 任务 2 在现场编写函数表达式. 在这种情况下,你可以接收事件作为第一个参数.

    html
    <button v-on:click="(e) => increment(e)">increment</button>
  • 任务 3 编写除函数以外的语句.

    html
    <button @click="count = 0">reset</button>

    看起来这个表达式需要转换为以下函数.

    ts
    ;() => {
      count = 0
    }
  • 任务 4 在像任务 3 这样的情况下,你可以使用标识符 $event. 这是处理事件对象的情况.

    ts
    const App = defineComponent({
      setup() {
        const count = ref(0)
        const increment = (e: Event) => {
          console.log(e)
          count.value++
        }
        return { count, increment, object }
      },
    
      template: `
        <div class="container">
          <button @click="increment($event)">increment($event)</button>
          <p> {{ count }} </p>
        </div>
        `,
    })
    // 不能像 @click="() => increment($event)" 这样使用。

    看起来它需要转换为以下函数.

    ts
    $event => {
      increment($event)
    }

实现

当没有 arg 时

暂时,让我们实现没有 arg 的情况,因为它与 v-bind 相同. 这是我在前一章中留下 TODO 注释的部分.它在 transformElement 附近.

ts
const isVBind = name === 'bind'
const isVOn = name === 'on' // --------------- 这里

// v-bind 和 v-on 没有参数的特殊情况
if (!arg && (isVBind || isVOn)) {
  if (exp) {
    if (isVBind) {
      pushMergeArg()
      mergeArgs.push(exp)
    } else {
      // -------------------------------------- 这里
      // v-on="obj" -> toHandlers(obj)
      pushMergeArg({
        type: NodeTypes.JS_CALL_EXPRESSION,
        loc,
        callee: context.helper(TO_HANDLERS),
        arguments: [exp],
      })
    }
  }
  continue
}

const directiveTransform = context.directiveTransforms[name]
if (directiveTransform) {
  const { props } = directiveTransform(prop, node, context)
  if (isVOn && arg && !isStaticExp(arg)) {
    pushMergeArg(createObjectExpression(props, elementLoc))
  } else {
    properties.push(...props)
  }
} else {
  // TODO: 自定义指令。
}

我将这次实现名为 TO_HANDLERS 的辅助函数.

这个函数将以 v-on="{ click: increment }" 形式传递的对象转换为 { onClick: increment } 的形式. 没有什么特别困难的.

ts
import { toHandlerKey } from '../../shared'

/**
 * 用于在 v-on="obj" 中为键添加 "on" 前缀
 */
export function toHandlers(obj: Record<string, any>): Record<string, any> {
  const ret: Record<string, any> = {}
  for (const key in obj) {
    ret[toHandlerKey(key)] = obj[key]
  }
  return ret
}

这完成了没有 arg 时的实现. 让我们继续实现有 arg 时的情况.

transformVOn

现在,让我们继续这次的主题,即 v-on.v-on 的 exp 有各种格式.

ts
increment

state.increment

count++

;() => count++

increment($event)

e => increment(e)

首先,这些格式可以大致分为两类:"函数"和"语句".在 Vue 中,如果是单个 Identifier,单个 MemberExpression 或函数表达式,则将其视为函数.否则,它是一个语句.在源代码中,它似乎被称为 inlineStatement.

ts
// 函数(※ 为了方便,请将这些视为函数表达式。)
increment
state.increment
;() => count++
e => increment(e)

// inlineStatement
count++
increment($event)

换句话说,这次的实现流程如下:

  1. 首先,确定它是否是函数(单个 Identifier 或单个 MemberExpression 或函数表达式).

2-1. 如果是函数,生成 eventName: exp 形式的 ObjectProperty,不进行任何转换.

2-2. 如果不是函数(如果是 inlineStatement),将其转换为 $event => { ${exp} } 的形式并生成 ObjectProperty.

这就是基本思路.

确定是函数表达式还是语句

让我们从实现确定开始.是否是函数表达式是使用正则表达式完成的.

ts
const fnExpRE =
  /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/

const isFn = fnExpRE.test(exp.content)

是否是单个 Identifier 或单个 MemberExpression 是用名为 isMemberExpression 的函数实现的.

ts
const isMemberExp = isMemberExpression(exp.content)

这个 isMemberExpression 函数相当复杂,实现很长.有点长,所以我在这里省略它.(如果你感兴趣,请查看代码.)

一旦我们确定了这一点,它是 inlineStatement 的条件就是除了这些之外的任何东西.

ts
const isMemberExp = isMemberExpression(exp.content)
const isFnExp = fnExpRE.test(exp.content)
const isInlineStatement = !(isMemberExp || isFnExp)

现在我们已经确定了这一点,让我们基于这个结果实现转换过程.

ts
const isMemberExp = isMemberExpression(exp.content)
const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content))
const hasMultipleStatements = exp.content.includes(`;`)

if (isInlineStatement) {
  // 将内联语句包装在函数表达式中
  exp = createCompoundExpression([
    `$event => ${hasMultipleStatements ? `{` : `(`}`,
    exp,
    hasMultipleStatements ? `}` : `)`,
  ])
}

问题

实际上,上述实现有一个小问题.

问题在于 $event,因为在 dir.exp 中,我们需要使用 processExpression 处理从 setup 绑定的值,但问题在于 $event. 在 AST 上,$event 也被视为 Identifier,所以如果我们保持原样,它将被加上 _ctx. 前缀.

所以让我们做一点改进.让我们在 transformContext 中注册一个局部变量.在 walkIdentifiers 中,如果有局部变量,我们不会执行 onIdentifier

ts
const context: TransformContext = {
  // .
  // .
  // .
  identifiers: Object.create(null),
  // .
  // .
  addIdentifiers(exp) {
    if (!isBrowser) {
      addId(exp)
    }
  },
  removeIdentifiers(exp) {
    if (!isBrowser) {
      removeId(exp)
    }
  },
}

function addId(id: string) {
  const { identifiers } = context
  if (identifiers[id] === undefined) {
    identifiers[id] = 0
  }
  identifiers[id]!++
}

function removeId(id: string) {
  context.identifiers[id]!--
}
ts
export function walkIdentifiers(
  root: Node,
  onIdentifier: (node: Identifier) => void,
  knownIds: Record<string, number> = Object.create(null), 
) {
  ;(walk as any)(root, {
    enter(node: Node) {
      if (node.type === 'Identifier') {
        const isLocal = !!knownIds[node.name] 
        // prettier-ignore
        if (!isLocal) { 
          onIdentifier(node);
        } 
      }
    },
  })
}

然后,当在 processExpression 中使用 walkIdentifiers 时,我们将从 context 中拉取 identifiers

ts
const ids: QualifiedId[] = []
const knownIds: Record<string, number> = Object.create(ctx.identifiers) 

walkIdentifiers(
  ast,
  node => {
    node.name = rewriteIdentifier(node.name)
    ids.push(node as QualifiedId)
  },
  knownIds, 
)

最后,当在 transformOn 中转换时,让我们注册 $event

ts
// prettier-ignore
if (!context.isBrowser) { 
  isInlineStatement && context.addIdentifiers(`$event`); 
  exp = dir.exp = processExpression(exp, context); 
  isInlineStatement && context.removeIdentifiers(`$event`); 
} 

if (isInlineStatement) {
  // 将内联语句包装在函数表达式中
  exp = createCompoundExpression([
    `$event => ${hasMultipleStatements ? `{` : `(`}`,
    exp,
    hasMultipleStatements ? `}` : `)`,
  ])
}

由于 v-on 需要一些特殊处理,并且由于它在 transformOn 中单独处理,我们将在 transformExpression 中跳过它.

ts
export const transformExpression: NodeTransform = (node, ctx) => {
  // .
  // .
  // .
  if (
    exp &&
    exp.type === NodeTypes.SIMPLE_EXPRESSION &&
    !(dir.name === 'on' && arg) 
  ) {
    dir.exp = processExpression(exp, ctx)
  }
}

现在,我们已经完成了这次的关键部分.让我们实现剩余的必要部分并完成 v-on!!

到此为止的源代码:GitHub

基于 MIT 许可证发布。