蓝色天空.知识 · 实践 · 创造
我的收藏
Vue3 教程目录 48章
Vue3 / LEARN BY DOING

Vue3 单文件组件

介绍 Vue 3 单文件组件(*.vue / SFC)的三段式结构、App.vue 与 main.js 最小工程启动、子组件注册复用以及 <script setup> 与 <style scoped> 样式隔离,并附离线 Chromium 实测。

学完这一章,你能够

  • 介绍 Vue 3 单文件组件(*.vue / SFC)的三段式结构、App.vue 与 main.js 最小工程启动、子组件注册复用以及 <script setup> 与 <style scoped> 样式隔离,并附离线 Chromium 实测。

单文件组件(SFC)结构与最小工程骨架

Vue 的单文件组件(Single-File Component,简称 SFC,扩展名为 `.vue`)将单个组件的 HTML 模板(`<template>`)、JavaScript 逻辑(`<script>`)与 CSS 样式(`<style>`)封装在同一文件内,兼顾关注点高内聚与构建期静态优化。

在通过 `npm init vue@latest`(或 `npm create vue@latest`)初始化 Vite 项目后,若想从零搭建最简页面,可清空 `src/assets` 与 `src/components` 中的示例文件,将 `App.vue` 精简为 `<script></script>`、`<template></template>`、`<style></style>` 三块空骨架,并在入口 `src/main.js` 中保留 `import { createApp } from 'vue'`、`import App from './App.vue'` 及 `createApp(App).mount('#app')`。

编写第一个 App.vue 单文件组件

在 `App.vue` 中,`<template>` 用 `<h1>{{ message }}</h1>` 绑定响应式文本,`<script>` 通过 ES 模块 `export default { data() { return { message: '...' } } }` 导出组件配置对象(无需像 Vue 2 那样全局调用 `Vue.component`),`<style>` 则定义标题为蓝色。在 Vite 开发服务器(默认 `http://localhost:5173/`)中,构建工具由 `@vitejs/plugin-vue` 自动将 `.vue` 编译为标准 ES 模块与样式。本站离线 Chromium 实测解析并挂载含三段块的 SFC 字符串后,DOM 渲染出 `Hello, Vue3 SFC!` 且 `getComputedStyle(h1).color` 为 `rgb(0, 0, 255)`。

创建、注册子组件与 <style scoped> 样式隔离

拆分子组件时,可在 `./src/components/` 下新建独立 `.vue` 文件(如标题为红色的子组件),在 `./src/main.js` 中导入并通过 `app.component('hello-card', HelloCard)` 全局注册(或在父组件内直接局部导入),随后即可在父组件 `App.vue` 的 `<template>` 中以自定义标签 `<hello-card></hello-card>` 复用。工程中通常进一步搭配 `<script setup>` 精简样板代码,并在 `<style scoped>` 中利用编译期生成的唯一属性(如 `data-v-xxxx`)将样式限定在当前组件内部。本站离线 Chromium 实测验证:注册子组件后成功渲染红色标题 `rgb(255, 0, 0)`;启用 `<style scoped>` 后,父组件 `h1`(`rgb(128, 0, 128)`)与子组件 `h1`(`rgb(0, 128, 0)`)各自附带独立作用域属性,样式严格隔离互不串扰。

在离线 Chromium 中解析挂载 SFC 三段块、注册子组件并验证 <style scoped> 隔离

含完整源码 · 251 行
展开查看收起
python
"""Offline Playwright Chromium lab for Vue 3 Ch 29: Single-File Components (SFC)."""
import json
from playwright.sync_api import sync_playwright


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 SFC Offline Lab</title>
</head>
<body>
  <div id="app1"></div>
  <div id="app2"></div>
  <div id="app3"></div>
<script>
// Offline SFC descriptor parser & scoped CSS compiler
function parseSFC(source) {
  const tplMatch = source.match(/<template>([\s\S]*?)<\/template>/);
  const scriptMatch = source.match(/<script(\s+setup)?>([\s\S]*?)<\/script>/);
  const styleMatch = source.match(/<style(\s+scoped)?>([\s\S]*?)<\/style>/);
  return {
    template: tplMatch ? tplMatch[1].trim() : '',
    script: scriptMatch ? scriptMatch[2].trim() : '',
    isScriptSetup: Boolean(scriptMatch && scriptMatch[1]),
    style: styleMatch ? styleMatch[2].trim() : '',
    isScoped: Boolean(styleMatch && styleMatch[1])
  };
}

function scopeCss(css, scopeAttr) {
  return css.replace(/([^{}]+)\{/g, (_, sel) => {
    const rewritten = sel.split(',').map(s => `${s.trim()}[${scopeAttr}]`).join(', ');
    return `${rewritten} {`;
  });
}

function compileAndMountSFC(sfcSource, mountEl, { scopeId = null, components = {} } = {}) {
  const desc = parseSFC(sfcSource);
  let state = {};
  if (desc.script) {
    if (desc.isScriptSetup) {
      const fn = new Function(desc.script + '\nreturn { message };');
      state = fn();
    } else {
      const mod = {};
      const code = desc.script.replace(/export\s+default/, 'mod.default =');
      new Function('mod', code)(mod);
      state = mod.default && mod.default.data ? mod.default.data() : {};
    }
  }

  let html = desc.template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k) => state[k] ?? '');
  const wrapper = document.createElement('div');
  wrapper.innerHTML = html;

  if (desc.isScoped && scopeId) {
    wrapper.querySelectorAll('*').forEach(el => el.setAttribute(scopeId, ''));
  }

  // Resolve registered child custom tags
  for (const [tagName, childSfc] of Object.entries(components)) {
    wrapper.querySelectorAll(tagName).forEach(placeholder => {
      const host = document.createElement('div');
      compileAndMountSFC(childSfc.source, host, { scopeId: childSfc.scopeId });
      placeholder.replaceWith(...host.childNodes);
    });
  }

  if (desc.style) {
    const styleEl = document.createElement('style');
    styleEl.textContent = (desc.isScoped && scopeId) ? scopeCss(desc.style, scopeId) : desc.style;
    document.head.appendChild(styleEl);
  }

  mountEl.innerHTML = '';
  mountEl.append(...wrapper.childNodes);
  return desc;
}

window.runSfcTests = function () {
  // Case 1: Basic App.vue with <template>, <script>, <style>
  const app1Sfc = `
<template>
  <div>
    <h1 id="h1-app1">{{ message }}</h1>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: 'Hello, Vue3 SFC!'
    }
  }
}
<\/script>
<style scoped>
h1 {
  color: blue;
}
</style>`;
  const d1 = compileAndMountSFC(app1Sfc, document.getElementById('app1'), { scopeId: 'data-v-app1' });
  const h1App1 = document.getElementById('h1-app1');

  // Case 2: Child SFC HelloCard.vue registered via app.component('hello-card', HelloCard)
  const helloCardSfc = `
<template>
  <div>
    <h1 id="h1-child">{{ message }}</h1>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: 'Hello, Child SFC!'
    }
  }
}
<\/script>
<style scoped>
h1 {
  color: red;
}
</style>`;
  const parentSfc = `
<template>
  <div>
    <hello-card></hello-card>
  </div>
</template>`;
  compileAndMountSFC(parentSfc, document.getElementById('app2'), {
    components: { 'hello-card': { source: helloCardSfc, scopeId: 'data-v-card' } }
  });
  const h1Child = document.getElementById('h1-child');

  // Case 3: <script setup> + <style scoped> isolation between parent and child h1
  const scopedChildSfc = `
<template>
  <h1 id="h1-scoped-child">{{ message }}</h1>
</template>
<script setup>
const message = 'Scoped Child Heading';
<\/script>
<style scoped>
h1 {
  color: green;
}
</style>`;
  const scopedParentSfc = `
<template>
  <section>
    <h1 id="h1-scoped-parent">{{ message }}</h1>
    <scoped-child></scoped-child>
  </section>
</template>
<script setup>
const message = 'Scoped Parent Heading';
<\/script>
<style scoped>
h1 {
  color: purple;
}
</style>`;
  const d3 = compileAndMountSFC(scopedParentSfc, document.getElementById('app3'), {
    scopeId: 'data-v-parent3',
    components: { 'scoped-child': { source: scopedChildSfc, scopeId: 'data-v-child3' } }
  });
  const h1P3 = document.getElementById('h1-scoped-parent');
  const h1C3 = document.getElementById('h1-scoped-child');

  return {
    case1: {
      blocks_found: Boolean(d1.template && d1.script && d1.style),
      text: h1App1.textContent,
      color: getComputedStyle(h1App1).color,
      has_scope_attr: h1App1.hasAttribute('data-v-app1')
    },
    case2: {
      child_text: h1Child.textContent,
      child_color: getComputedStyle(h1Child).color,
      has_child_scope: h1Child.hasAttribute('data-v-card')
    },
    case3: {
      script_setup: d3.isScriptSetup,
      parent_text: h1P3.textContent,
      parent_color: getComputedStyle(h1P3).color,
      child_text: h1C3.textContent,
      child_color: getComputedStyle(h1C3).color,
      styles_isolated: getComputedStyle(h1P3).color !== getComputedStyle(h1C3).color
    }
  };
};
</script>
</body>
</html>
"""


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)
        out = page.evaluate("window.runSfcTests()")
        browser.close()

    expected = {
        "sfc_block_parsing_and_render": {
            "blocks_found": True,
            "text": "Hello, Vue3 SFC!",
            "color": "rgb(0, 0, 255)",
            "has_scope_attr": True,
        },
        "child_sfc_registration_and_mount": {
            "child_text": "Hello, Child SFC!",
            "child_color": "rgb(255, 0, 0)",
            "has_child_scope": True,
        },
        "script_setup_and_scoped_style_isolation": {
            "script_setup": True,
            "parent_text": "Scoped Parent Heading",
            "parent_color": "rgb(128, 0, 128)",
            "child_text": "Scoped Child Heading",
            "child_color": "rgb(0, 128, 0)",
            "styles_isolated": True,
        },
    }
    mapping = [
        ("sfc_block_parsing_and_render", out["case1"]),
        ("child_sfc_registration_and_mount", out["case2"]),
        ("script_setup_and_scoped_style_isolation", out["case3"]),
    ]
    cases = [
        {"name": name, "expected": expected[name], "actual": actual, "passed": actual == expected[name]}
        for name, actual in mapping
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对 .vue 三段块解析渲染与蓝色标题计算样式、子组件自定义标签注册渲染红色标题,以及 <script setup> + <style scoped> 属性改写确保父子 h1 样式互不污染。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a801.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Vue3

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip

下载课程关联工程包:Vue3

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a830.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

.vue 是 Vue 自定义格式,需在构建或开发服务器阶段经由 @vitejs/plugin-vue / @vue/compiler-sfc 编译为标准 JS 渲染函数与 CSS;<style scoped> 会为当前组件模板元素添加唯一的 data-v-xxxx 属性,并将样式选择器改写为带该属性选择器的规则。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习