Vue3 博客项目
从零搭建 Vue 3 博客项目:核对 Node.js/npm 环境要求、create-vue 交互选项与目录职责、单文件组件(SFC)三段式结构与 scoped 样式隔离、模板语法对比 JSX,并在 Chromium 中实测博客基础骨架。
学完这一章,你能够
- 从零搭建 Vue 3 博客项目:核对 Node.js/npm 环境要求、create-vue 交互选项与目录职责、单文件组件(SFC)三段式结构与 scoped 样式隔离、模板语法对比 JSX,并在 Chromium 中实测博客基础骨架。
环境准备与 create-vue 工程初始化
Vue 3 博客项目依托 Node.js 运行时与 npm 包管理器驱动 Vite 工具链。开始前在终端运行 `node -v`(建议 v16 及以上,如 `v20.10.0`;未安装可从 nodejs.org 获取 LTS 版本)与 `npm -v` 核验基础环境。
官方推荐使用 `npm create vue@latest blog-app` 初始化工程,在交互向导中开启 Vue Router 与 Pinia、其余入门阶段保持 `No`(详见下表)。随后依次执行 `cd blog-app`、`npm install`(联网按 `package.json` 下载依赖至 `node_modules`)与 `npm run dev`,即可在 `http://localhost:5173` 启动默认欢迎页。
`blog-app` 目录包含 11 个核心目录与文件:`index.html` 作为浏览器入口,由 Vite 自动注入 `src/main.js`;`src/main.js` 负责创建 Vue 实例、注册路由与 Pinia 并挂载到页面;`src/App.vue` 是承载导航栏、页脚与路由出口的根组件;`public/` 存放不经编译的静态文件,`src/assets/`、`components/`、`views/`、`router/`、`stores/` 按职责分层。本站清单核对确认 6 项向导配置(仅 Router 与 Pinia 为 `Yes`)与 11 项目录条目完整一致。
单文件组件(SFC)与模板语法 vs JSX
每个 `.vue` 文件都是一个单文件组件(Single File Component),将逻辑 `<script setup>`、结构 `<template>` 与样式 `<style scoped>` 封装在独立单元中;三段顺序虽无硬性限制,但业界惯例写作 `script -> template -> style`,其中 `scoped` 通过属性选择器将 CSS 限定在当前组件内部而不污染兄弟组件。本站 Chromium 实测 SFC 解析与样式隔离:块顺序为 `['script', 'template', 'style']`,带作用域属性的组件 A 标题渲染为 `Hello Vue3!` 且颜色为 Vue 绿 `rgb(66, 184, 131)`,而未带该属性的相邻组件 B 标题维持默认 `rgb(51, 51, 51)`。
Vue 默认推荐写在 `<template>` 中的声明式模板语法(HTML + Vue 指令),同时也提供可选的 JSX 支持;二者编译后都生成一致的渲染结果。本站实测确认:声明式模板与 hyperscript/JSX 风格工厂渲染出的 `<article><h2>My Blog</h2><span>3 篇</span></article>` DOM 完全等价,博客全系列将采用更直观的模板语法。
动手搭建博客基础骨架与小结
清空默认 `App.vue` 后,即可写出由顶部 `.navbar`、中间 `.container` 与底部 `.footer` 组成的博客骨架。本站 Chromium(`1280x800`)渲染实测核对:`.navbar` 为 `display: flex` 且 `justify-content: space-between`,品牌标题 `My Blog` 计算色值为 `rgb(66, 184, 131)`,导航链接为 `['首页', '关于']`,主内容区 `max-width` 为 `960px`,页脚居中显示 `© 2024 My Blog. Powered by Vue3.`。至此已掌握项目创建、目录结构、SFC 三段式与博客骨架。
create-vue 脚手架交互选项配置
| 选项 | 选择 | 说明 |
|---|---|---|
| Add TypeScript? | No | 入门阶段优先使用纯 JavaScript 降低学习门槛 |
| Add JSX Support? | No | 直接使用 Vue 默认模板语法更贴近原生 HTML |
| Add Vue Router? | Yes | 后续博客文章详情与多页面导航需要路由支持 |
| Add Pinia? | Yes | 后续跨组件共享博客状态时使用 Pinia 仓库 |
| Add Vitest? | No | 当前入门项目暂不配置单元测试框架 |
| Add ESLint? | No | 初学阶段暂不引入额外代码规范检查配置 |
单文件组件(SFC)三段式区块说明
| 区块 | 作用 | 一句话理解 |
|---|---|---|
| <script setup> | 编写 JavaScript 逻辑、定义响应式数据与交互方法 | 控制组件做什么 |
| <template> | 编写 HTML 视图结构并绑定数据与指令 | 控制组件长什么样 |
| <style scoped> | 编写仅作用于当前组件的局部 CSS 样式 | 控制组件好不好看 |
Vue 模板语法与 JSX 对比
| 特性 | 模板语法 | JSX |
|---|---|---|
| 语法形式 | 标准 HTML 结合 Vue 指令 | 在 JavaScript 中编写类 HTML 表达式 |
| 学习成本 | 较低,熟悉 HTML 即可快速上手 | 需要理解 JSX 转译与渲染函数机制 |
| 灵活性 | 中等,以声明式描述视图为主 | 很高,可借助完整 JS 能力动态组装界面 |
| Vue 推荐度 | 官方默认推荐方案 | 作为可选高级能力支持 |
| 适用场景 | 绝大多数常规业务与博客页面开发 | 需要高度动态编排逻辑的复杂渲染组件 |
实测 Vue 3 博客骨架排版、SFC scoped 样式隔离与模板/JSX 等价渲染
"""Offline Playwright Chromium lab for Vue3 Ch39: Blog project scaffold, SFC & skeleton."""
import json
from playwright.sync_api import sync_playwright
HTML = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>Vue3 Blog Project Lab</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f5f5f5;
color: #333;
}
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 40px;
background: #fff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.navbar h1 { font-size: 24px; color: #42b883; }
.navbar a { margin-left: 20px; text-decoration: none; color: #333; }
.container { max-width: 960px; margin: 40px auto; padding: 0 20px; }
.footer { text-align: center; padding: 20px; color: #999; border-top: 1px solid #eee; }
/* Simulated Vue SFC scoped CSS isolation */
h1[data-v-sfc1] { color: #42b883; }
</style>
</head>
<body>
<div id="app">
<header class="navbar">
<h1>My Blog</h1>
<nav>
<a href="/">首页</a>
<a href="#">关于</a>
</nav>
</header>
<main class="container">
<p>博客内容将在这里展示</p>
<section id="sfc-demo">
<div id="comp-a"><h1 data-v-sfc1>Hello Vue3!</h1></div>
<div id="comp-b"><h1>Other Heading</h1></div>
</section>
<section id="tpl-vs-jsx">
<div id="tpl-out"></div>
<div id="jsx-out"></div>
</section>
</main>
<footer class="footer">
<p>© 2024 My Blog. Powered by Vue3.</p>
</footer>
</div>
<script>
const sfcSample = `<script setup>
const message = 'Hello Vue3!'
<\/script>
<template>
<h1>{{ message }}</h1>
</template>
<style scoped>
h1 { color: #42b883; }
</style>`;
window.__inspectSfc = function() {
const blocks = [...sfcSample.matchAll(/<(script|template|style)\b[^>]*>/g)].map(m => m[1]);
return {
blockOrder: blocks,
hasScopedAttr: sfcSample.includes('<style scoped>'),
compAColor: getComputedStyle(document.querySelector('#comp-a h1')).color,
compBColor: getComputedStyle(document.querySelector('#comp-b h1')).color,
compAText: document.querySelector('#comp-a h1').textContent
};
};
window.__compareTemplateVsJsx = function() {
const data = { title: 'My Blog', count: 3 };
// Template syntax render
document.getElementById('tpl-out').innerHTML = `<article><h2>${data.title}</h2><span>${data.count} 篇</span></article>`;
// JSX / hyperscript render
function h(tag, children) {
const el = document.createElement(tag);
for (const c of children) el.append(typeof c === 'string' ? document.createTextNode(c) : c);
return el;
}
document.getElementById('jsx-out').appendChild(
h('article', [h('h2', [data.title]), h('span', [`${data.count} 篇`])])
);
return {
tplHtml: document.getElementById('tpl-out').innerHTML,
jsxHtml: document.getElementById('jsx-out').innerHTML,
equivalentDom: document.getElementById('tpl-out').innerHTML === document.getElementById('jsx-out').innerHTML
};
};
window.__scaffoldSpec = {
minNodeMajor: 16,
options: {
'Add TypeScript?': 'No',
'Add JSX Support?': 'No',
'Add Vue Router?': 'Yes',
'Add Pinia?': 'Yes',
'Add Vitest?': 'No',
'Add ESLint?': 'No'
},
structure: [
'index.html', 'package.json', 'vite.config.js', 'public/',
'src/main.js', 'src/App.vue', 'src/assets/', 'src/components/',
'src/views/', 'src/router/', 'src/stores/'
]
};
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1280, "height": 800})
page.set_content(HTML, wait_until="domcontentloaded")
# Case 1: Blog skeleton layout & computed styles
act1 = page.evaluate("""() => {
const nav = getComputedStyle(document.querySelector('.navbar'));
const h1 = getComputedStyle(document.querySelector('.navbar h1'));
const main = getComputedStyle(document.querySelector('.container'));
const footer = getComputedStyle(document.querySelector('.footer'));
return {
brandText: document.querySelector('.navbar h1').textContent,
brandColor: h1.color,
navDisplay: nav.display,
navJustify: nav.justifyContent,
navLinks: [...document.querySelectorAll('.navbar a')].map(a => a.textContent),
containerMaxWidth: main.maxWidth,
footerAlign: footer.textAlign,
footerText: document.querySelector('.footer p').textContent
};
}""")
exp1 = {
"brandText": "My Blog",
"brandColor": "rgb(66, 184, 131)",
"navDisplay": "flex",
"navJustify": "space-between",
"navLinks": ["首页", "关于"],
"containerMaxWidth": "960px",
"footerAlign": "center",
"footerText": "© 2024 My Blog. Powered by Vue3.",
}
cases.append({"name": "blog_skeleton_layout_and_styles", "expected": exp1, "actual": act1, "passed": act1 == exp1})
# Case 2: SFC 3-block order & scoped CSS isolation
act2 = page.evaluate("window.__inspectSfc()")
exp2 = {
"blockOrder": ["script", "template", "style"],
"hasScopedAttr": True,
"compAColor": "rgb(66, 184, 131)",
"compBColor": "rgb(51, 51, 51)",
"compAText": "Hello Vue3!",
}
cases.append({"name": "sfc_three_blocks_and_scoped_css", "expected": exp2, "actual": act2, "passed": act2 == exp2})
# Case 3: Template syntax vs JSX DOM equivalence
act3 = page.evaluate("window.__compareTemplateVsJsx()")
exp3 = {
"tplHtml": "<article><h2>My Blog</h2><span>3 篇</span></article>",
"jsxHtml": "<article><h2>My Blog</h2><span>3 篇</span></article>",
"equivalentDom": True,
}
cases.append({"name": "template_syntax_vs_jsx_equivalence", "expected": exp3, "actual": act3, "passed": act3 == exp3})
# Case 4: create-vue scaffold options & directory layout manifest
act4 = page.evaluate("""() => {
const s = window.__scaffoldSpec;
const yesKeys = Object.entries(s.options).filter(([, v]) => v === 'Yes').map(([k]) => k);
return {
minNodeMajor: s.minNodeMajor,
optionCount: Object.keys(s.options).length,
yesKeys,
structureCount: s.structure.length,
hasCoreEntryFiles: ['index.html', 'src/main.js', 'src/App.vue'].every(f => s.structure.includes(f))
};
}""")
exp4 = {
"minNodeMajor": 16,
"optionCount": 6,
"yesKeys": ["Add Vue Router?", "Add Pinia?"],
"structureCount": 11,
"hasCoreEntryFiles": True,
}
cases.append({"name": "scaffold_options_and_structure_spec", "expected": exp4, "actual": act4, "passed": act4 == exp4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对博客导航栏 Flex 排版与 #42b883 品牌色、960px 主内容容器、scoped 局部样式不泄漏到相邻组件,以及模板语法与 JSX 产出完全一致的 DOM。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:7d44f6148ebf4ba29c1caf17b8976269ecfe0fda1bb28a3c60dae7f0b6c88d11
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:0fe78cd3b24b7c194f8cd9ece31c2d5722eb3f6ce6806c4d820d7cdbf4fe0933
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Vue 3 项目中,public/ 目录与 src/assets/ 目录存放静态资源有什么区别?
展开参考解答
src/assets/ 中的 CSS 和图片会经过 Vite 构建打包(如内联优化、生成内容哈希文件名),适合组件内相对路径引用;public/ 中的文件不经过构建编译,会原样复制到打包输出根目录供绝对路径直接访问。