Vue3 单文件组件是如何工作的

267 阅读2分钟

单文件组件.vue

Vue 的单文件组件 (即 *.vue 文件,英文 Single-File Component,简称 SFC) 是一种特殊的文件格式,使我们能够将一个 Vue 组件的模板、逻辑与样式封装在单个文件中。

.vue编译

屏幕截图 2025-05-27 120338.png

Vue 单文件组件是一个框架指定的文件格式,因此必须交由 @vue/compiler-sfc 编译为标准的 JavaScript 和 CSS,一个编译后的单文件组件是一个标准的 JavaScript(ES) 模块,可以像导入其他 ES 模块一样导入单文件组件。

import MyComponent from './MyComponent.vue' 

单文件组件中的 <style> 标签一般会在开发时注入成原生的 <style> 标签以支持热更新,而生产环境下它们会被抽取、合并成单独的 CSS 文件。

在实际项目中,我们一般会使用集成了单文件组件编译器的构建工具,比如 Vite 或者 Vue CLI (基于 webpack)。

template编译

屏幕截图 2025-05-27 121307.png

vue提供tempalte和render两种方式API编写UI,使用template编写UI,需要将template编译成render。编译成render有两种方式:

  1. 完全版的Vue包含了编译器,支持在浏览器中直接编译模板。
  2. 只包含运行时的版本不包含编译器,template在构建时预先编译。

默认的工具链中都会使用仅含运行时的版本,因为所有单文件组件中的模板都已经被预编译了。

.vue文件编译代码

单文件组件App.vue:

<script setup>
import { ref } from 'vue'

const msg = ref('Hello World!')
</script>

<template>
  <h1>{{ msg }}</h1>
  <input v-model="msg" />
</template>

单文件组件App.vue编译成javascript:

/* Analyzed bindings: {
  "ref": "setup-const",
  "msg": "setup-ref"
} */
import { ref } from 'vue'


const __sfc__ = {
  __name: 'App',
  setup(__props, { expose: __expose }) {
  __expose();

const msg = ref('Hello World!')

const __returned__ = { msg, ref }
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
return __returned__
}

};
import { toDisplayString as _toDisplayString, createElementVNode as _createElementVNode, vModelText as _vModelText, withDirectives as _withDirectives, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue"
function render(_ctx, _cache, $props, $setup, $data, $options) {
  return (_openBlock(), _createElementBlock(_Fragment, null, [
    _createElementVNode("h1", null, _toDisplayString($setup.msg), 1 /* TEXT */),
    _withDirectives(_createElementVNode("input", {
      "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.msg) = $event))
    }, null, 512 /* NEED_PATCH */), [
      [_vModelText, $setup.msg]
    ])
  ], 64 /* STABLE_FRAGMENT */))
}
__sfc__.render = render
__sfc__.__file = "src/App.vue"
export default __sfc__

参考:
(1)单文件组件
(2)Vue 单文件组件演练场