Vue代码编译之后是怎么显示的?

251 阅读1分钟

官网链接,可以体会一下vue每行代码编译之后的显示

Vue Template 编译成js代码是怎么样的?

具体的代码如下:

<div>
  <div class="title" style={{margin: 10}}>foo</div>
  <p>文字显示</p>
  <div>bar</div>
  <div>{{test}}</div>
  <div v-if="dynamic">{{ dynamic }}</div>
</div>

编译的代码如下:

import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode } from "vue"

const _hoisted_1 = /*#__PURE__*/_createElementVNode("div", {
  class: "title",
  style: {},
  "10}}": ""
}, "foo", -1 /* HOISTED */)
const _hoisted_2 = /*#__PURE__*/_createElementVNode("p", null, "文字显示", -1 /* HOISTED */)
const _hoisted_3 = /*#__PURE__*/_createElementVNode("div", null, "bar", -1 /* HOISTED */)
const _hoisted_4 = { key: 0 }

export function render(_ctx, _cache, $props, $setup, $data, $options) {
  return (_openBlock(), _createElementBlock("div", null, [
    _hoisted_1,
    _hoisted_2,
    _hoisted_3,
    _createElementVNode("div", null, _toDisplayString(_ctx.test), 1 /* TEXT */),
    (_ctx.dynamic)
      ? (_openBlock(), _createElementBlock("div", _hoisted_4, _toDisplayString(_ctx.dynamic), 1 /* TEXT */))
      : _createCommentVNode("v-if", true)
  ]))
}

// Check the console for the AST

vue在静态的字符串会使用innerHTML进行直接渲染,如果是使用其他变量加载的会渲染成 _createElementBlock 这种方式,诸如此类vue编译之后的代码,具体怎样渲染可以看官网的渲染机制这个标题的文档

vue3.x渲染机制