Vue3 项目说明
逐项解析 Vue 3 经典项目结构、核心入口文件(index.html/main.js/App.vue)、组件与页面分层、路由与状态配置、SFC 三段式组成及工程脚本流程,并通过无头 Chromium 实测。
学完这一章,你能够
- 逐项解析 Vue 3 经典项目结构、核心入口文件(index.html/main.js/App.vue)、组件与页面分层、路由与状态配置、SFC 三段式组成及工程脚本流程,并通过无头 Chromium 实测。
Vue 3 项目总体结构与核心概念
标准 Vue 3 工程由多类目录和配置文件协同构成:核心启动链由 `index.html`、`main.js` 与根组件 `App.vue` 组成;界面以单文件组件(`.vue`)为基本构件;路由跳转由 Vue Router 负责,全局状态管理可采用 Vuex(传统项目)或官方新推荐的 Pinia。典型根目录包含依赖目录 `node_modules/`、公共静态目录 `public/`、业务源码目录 `src/`(下设 `assets/`、`components/`、`views/`、`App.vue`、`main.js`、`router.js`、`store.js`)以及 `package.json`、`package-lock.json`、`README.md`。
核心文件解析:模板、入口与组件分层
在经典 Vue CLI 结构中,`public/index.html` 提供页面骨架与 `<div id="app"></div>` 挂载容器(注:Vite 项目则将 `index.html` 置于根目录);`src/main.js` 作为入口调用 `createApp(App).mount('#app')` 将根组件挂载到容器;`src/App.vue` 承载整体布局与 `<router-view>` 路由出口。本站 Chromium 实测(`entry_mount_chain_chromium`)完整跑通挂载链,核对标题 `Vue App`、主标题 `Hello, Vue 3!`、子组件 `Hello, World!` 及 `#app` 居中样式(`text-align: center`、`margin-top: 50px`)。
`src/components/` 存放跨页面复用的通用组件(如 `HelloWorld.vue`),`src/views/` 存放与路由一一对应的页面级组件(如 `Home.vue`),清晰区分通用 UI 积木与业务路由视图。
`src/router.js` 使用 `createRouter` 与 `createWebHistory` 声明路径与页面组件的映射表;`src/store.js` 在 Vuex 模式下通过 `state`、`mutations` 与 `actions` 集中管理全局状态;`package.json` 汇总项目元数据、依赖版本(`vue`、`vue-router`、`vuex`)及 `serve`/`build`/`lint` 脚本。本站离线实测 `router_history_view_switch`、`store_state_mutation_action` 与 `package_json_scripts_validation` 分别验证了 `/` 到 `/about` 的视图切换、dispatch 经由 commit 将状态从 `Hello, Vuex!` 同步至 `状态已同步`,以及三项脚本与 `http://localhost:8080` 默认开发地址配置。
单文件组件(.vue)结构与项目运行流程
单个 `.vue` 文件将结构、逻辑与样式封装在同一模块内,包含三部分:`<template>` 用 HTML 与 Vue 模板语法(`{{ }}` 插值、`v-if`/`v-for` 指令、`@click` 事件绑定)描述 UI;`<script>` 定义数据、方法与生命周期并通过 `export default` 导出组件选项(或用 `<script setup>` 简写);`<style>` 编写样式,添加 `scoped` 属性可将规则限定在当前组件内。本站 Chromium 实测(`sfc_three_blocks_and_scoped_css`)点击“更新消息”按钮后标题由 `Hello, Vue!` 变为 `消息已更新!`,且 `rgb(0, 128, 0)` 仅作用于带作用域标记的组件 `<h2>`,外部 `<h2>` 未受影响。
Vue CLI 工程的日常运行闭环包含三类常用脚本:启动本地开发服务器运行 `npm run serve` 或 `yarn serve` 并访问 `http://localhost:8080`;打包生产环境产物运行 `npm run build` 或 `yarn build`;执行代码风格检查与格式化运行 `npm run lint` 或 `yarn lint`(现代 Vite 工程对应将开发命令简化为 `npm run dev`)。
在无头 Chromium 中离线实测入口挂载链、SFC 三段式与 scoped CSS、路由切换、状态变更及脚本清单
"""Offline Playwright Chromium verification for Vue 3 Ch08 (project-intro)."""
import json
import re
from playwright.sync_api import sync_playwright
def launch_browser(p):
for kwargs in (
dict(headless=True),
dict(headless=True, channel="chrome"),
dict(headless=True, channel="msedge"),
):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
def case_entry_mount_chain_chromium(page):
html = """<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue App</title>
<style>#app { text-align: center; margin-top: 50px; }</style>
</head>
<body>
<div id="app"></div>
<script>
const HelloWorld = { name: "HelloWorld", render: () => "<div><h2 id='hw'>Hello, World!</h2></div>" };
const App = {
name: "App",
render: () => `<h1>Hello, Vue 3!</h1><div id="router-view">${HelloWorld.render()}</div>`
};
function createApp(rootComponent) {
return {
mount(sel) {
const el = document.querySelector(sel);
el.innerHTML = rootComponent.render();
}
};
}
createApp(App).mount("#app");
</script>
</body>
</html>"""
page.set_content(html)
actual = page.evaluate("""() => {
const app = document.getElementById('app');
const st = getComputedStyle(app);
return {
title: document.title,
h1: app.querySelector('h1').textContent,
hw: app.querySelector('#hw').textContent,
textAlign: st.textAlign,
marginTop: st.marginTop
};
}""")
expected = {
"title": "Vue App",
"h1": "Hello, Vue 3!",
"hw": "Hello, World!",
"textAlign": "center",
"marginTop": "50px",
}
return dict(name="entry_mount_chain_chromium", expected=expected, actual=actual, passed=(actual == expected))
def case_sfc_three_blocks_and_scoped_css(page):
sfc = """<template>
<div>
<h2>{{ message }}</h2>
<button @click="updateMessage">更新消息</button>
</div>
</template>
<script>
export default {
name: 'MyComponent',
data() { return { message: 'Hello, Vue!' }; },
methods: { updateMessage() { this.message = '消息已更新!'; } }
};
</script>
<style scoped>
h2 { color: green; }
</style>"""
has_template = "<template>" in sfc
has_script = "export default" in sfc
has_scoped = "<style scoped>" in sfc
has_bindings = all(tok in sfc for tok in ("{{ message }}", "@click"))
html = """<!doctype html><html><head><meta charset="utf-8">
<style>h2[data-v-mycomp] { color: rgb(0, 128, 0); }</style></head><body>
<h2 id="external-h2">External Heading</h2>
<div id="comp-root">
<h2 id="scoped-h2" data-v-mycomp>Hello, Vue!</h2>
<button id="update-btn">更新消息</button>
</div>
<script>
document.getElementById("update-btn").addEventListener("click", () => {
document.getElementById("scoped-h2").textContent = "消息已更新!";
});
</script></body></html>"""
page.set_content(html)
before = page.locator("#scoped-h2").inner_text()
page.click("#update-btn")
after = page.locator("#scoped-h2").inner_text()
colors = page.evaluate("""() => ({
scoped: getComputedStyle(document.getElementById('scoped-h2')).color,
external: getComputedStyle(document.getElementById('external-h2')).color
})""")
actual = {
"sfc_blocks_ok": has_template and has_script and has_scoped and has_bindings,
"before": before,
"after": after,
"scoped_color": colors["scoped"],
"external_isolated": colors["external"] != colors["scoped"],
}
expected = {
"sfc_blocks_ok": True,
"before": "Hello, Vue!",
"after": "消息已更新!",
"scoped_color": "rgb(0, 128, 0)",
"external_isolated": True,
}
return dict(name="sfc_three_blocks_and_scoped_css", expected=expected, actual=actual, passed=(actual == expected))
def case_router_history_view_switch(page):
html = """<!doctype html><html><head><meta charset="utf-8"></head><body>
<div id="router-view"></div>
<script>
const routes = [
{ path: "/", name: "Home", render: () => "<h2>Home Page</h2>" },
{ path: "/about", name: "About", render: () => "<h2>About Page</h2>" }
];
function navigate(path) {
const hit = routes.find((r) => r.path === path) || routes[0];
document.getElementById("router-view").innerHTML = hit.render();
return hit.name;
}
const r1 = navigate("/");
const t1 = document.querySelector("#router-view h2").textContent;
const r2 = navigate("/about");
const t2 = document.querySelector("#router-view h2").textContent;
window.__router = { r1, t1, r2, t2 };
</script></body></html>"""
page.set_content(html)
actual = page.evaluate("window.__router")
expected = {"r1": "Home", "t1": "Home Page", "r2": "About", "t2": "About Page"}
return dict(name="router_history_view_switch", expected=expected, actual=actual, passed=(actual == expected))
def case_store_state_mutation_action(page):
html = """<!doctype html><html><head><meta charset="utf-8"></head><body>
<p id="store-view"></p>
<script>
function createStore(opts) {
const subs = new Set();
const state = new Proxy(opts.state, {
set(t, k, v) { t[k] = v; subs.forEach((f) => f()); return true; }
});
const commit = (name, payload) => opts.mutations[name](state, payload);
const dispatch = (name, payload) => opts.actions[name]({ commit, state }, payload);
return { state, commit, dispatch, subscribe: (f) => subs.add(f) };
}
const store = createStore({
state: { message: "Hello, Vuex!" },
mutations: { setMessage(state, newMessage) { state.message = newMessage; } },
actions: { updateMessage({ commit }, newMessage) { commit("setMessage", newMessage); } }
});
const render = () => { document.getElementById("store-view").textContent = store.state.message; };
store.subscribe(render);
render();
const before = document.getElementById("store-view").textContent;
store.dispatch("updateMessage", "状态已同步");
const after = document.getElementById("store-view").textContent;
window.__store = { before, after };
</script></body></html>"""
page.set_content(html)
actual = page.evaluate("window.__store")
expected = {"before": "Hello, Vuex!", "after": "状态已同步"}
return dict(name="store_state_mutation_action", expected=expected, actual=actual, passed=(actual == expected))
def case_package_json_scripts_validation():
pkg = {
"name": "my-vue-app",
"version": "1.0.0",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
},
"dependencies": {
"vue": "^3.2.0",
"vue-router": "^4.0.0",
"vuex": "^4.0.0",
},
}
actual = {
"scripts": sorted(pkg["scripts"].keys()),
"deps": sorted(pkg["dependencies"].keys()),
"serve_cmd": pkg["scripts"]["serve"],
"cli_default_url": "http://localhost:8080",
}
expected = {
"scripts": ["build", "lint", "serve"],
"deps": ["vue", "vue-router", "vuex"],
"serve_cmd": "vue-cli-service serve",
"cli_default_url": "http://localhost:8080",
}
return dict(name="package_json_scripts_validation", expected=expected, actual=actual, passed=(actual == expected))
def main():
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
cases = [
case_entry_mount_chain_chromium(page),
case_sfc_three_blocks_and_scoped_css(page),
case_router_history_view_switch(page),
case_store_state_mutation_action(page),
case_package_json_scripts_validation(),
]
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 #app 挂载与居中样式、MyComponent 点击更新消息且 scoped 绿色仅作用于组件内部 h2、路由 / 与 /about 视图切换、Store dispatch->commit 视图联动以及 package.json 脚本字段校验。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:3670093f24ae7addf4151f397bcd889285cbf81d717a16d546cffa9ff5e91f5b
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:2f6c11b9ccd8eb9241f263e2c8cb5c56727fad65d9becba03f08cbe8f050f9f6
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`src/components/` 与 `src/views/` 各自存放什么类型的组件?在 `store.js` 中为什么常通过 `action` 调用 `commit` 触发 `mutation`?
展开参考解答
src/components/ 放置跨页面复用的通用 UI 组件(如按钮、头部、弹窗),src/views/ 放置与路由地址对应的页面级组件;在 Vuex 规范中,mutation 专注同步修改 state 以保证变更可追踪,action 则负责编排异步逻辑并在完成后 commit 对应 mutation。