← 返回完整题库
vue.js中等

vue 是如何识别和解析指令的?

参考答案

解析链路

Vue 3 的模板编译分三阶段,指令在 parse 与 transform 阶段被识别,在 generate 阶段变成等效代码。

  1. parse:parseHTML 逐段扫描标签/属性/文本/插值/注释,区分出 v-xxx、:xxx、@xxx、#xxx 形式的属性。
  2. 识别指令(Vue 2 的 parseDirectives 为例):
const dirRE = /^v-|^@|^:|^#/
if (dirRE.test(attr.name)) {
  const arg = attr.name.split(':')[1]
  addDirective(el, name, rawName, value, arg, modifiers)
}

匹配规则:v- 前缀或简写前缀 → 解析 dirName(去掉 v-、取 : 前的部分)、arg(: 后)、modifiers(. 后集合)。

  1. transform:
  • Vue 2:processIf/processFor/processOnce 重排 AST(v-for 包一层 For 节点、v-if 拆分支),其余指令交 platformDirectives(model/show/text/html)与自定义指令;
  • Vue 3:transformElement 收集指令进 props,buildProps 把 v-model 拆成 modelValue + onUpdate:modelValue,v-show 生成 vShow 指令,自定义指令进 directives 数组,同时做静态提升与 patchFlag。
  1. generate:内置指令不再出现在代码里,而是变成等效写法——v-if → 三元 + 注释占位、v-for → renderList、v-model → prop+event、v-show → 运行时 vShow、自定义指令 → withDirectives(vnode, [[dir, binding]])。

运行时

自定义指令在 mount/patch/unmount 时由 invokeDirectiveHook 按 created/beforeMount/mounted/beforeUpdate/updated/unmounted 调用;Vue 3 另有 getSSRProps。

一句话:指令不是运行时扫描字符串,而是编译期识别 + 转换 + 生成等效代码。

本题来自 计算机知识面试题库,共 921 道题。