Vue.js 目录结构
核对 Vue 2 Webpack 模板项目的根目录与 src 子目录职责表、App.vue 单文件组件结构,以及修改 Hello.vue 后在离线 Chromium 中的实时更新表现。
学完这一章,你能够
- 核对 Vue 2 Webpack 模板项目的根目录与 src 子目录职责表、App.vue 单文件组件结构,以及修改 Hello.vue 后在离线 Chromium 中的实时更新表现。
Webpack 模板根目录与 src 开发目录解析
使用 `vue-cli` Webpack 模板初始化并安装依赖后,在主流 IDE(如 VS Code、WebStorm 等)中打开项目根目录,可以看到构建脚本、配置目录、第三方依赖、业务源码、静态资源、测试目录及工程描述文件分层排布。本站离线实验在临时工作区重建了完整根目录骨架,核验出 `build`、`config`、`node_modules`、`src`、`static`、`test` 6 个顶层目录、`.babelrc`/`.editorconfig`/`.eslintrc.js`/`.gitignore` 4 类点号配置文件以及 `index.html`、`package.json`、`README.md` 3 个根目录文件。
日常业务编码主要集中在 `src` 目录内,其中包含四个核心部分:`assets` 存放会被构建工具打包处理的图片等资源(如 `logo.png`);`components` 存放可复用的子组件文件(小型演示中也可按需省略);`App.vue` 作为根组件入口,负责组织顶层模板与样式;`main.js` 则是应用启动核心文件,负责引入 Vue、挂载根组件并绑定至宿主 HTML 节点。
单文件组件 App.vue 与 Hello.vue 实测
Vue 单文件组件(`.vue`)将 `<template>` 展示模板、`<script>` 组件逻辑与 `<style>` 样式封装在同一文件中。以 `src/App.vue` 为例,模板内声明 `#app` 容器、引用 `./assets/logo.png` 并渲染 `<hello></hello>` 子组件;脚本通过 `import Hello from './components/Hello'` 导入并在 `components` 中注册;样式为 `#app` 设置居中对齐、深青灰字体色 `#2c3e50` 与 `60px` 顶部外边距。本站离线 Chromium 实测验证 `App.vue` 挂载后的组件注册关系与计算样式:`textAlign` 为 `center`、`color` 为 `rgb(44, 62, 80)`、`marginTop` 为 `60px`。
进一步修改 `src/components/Hello.vue`,在 `data()` 函数返回对象中更新 `msg` 字段即可改变视图内容;在本地开发服务器运行状态下,保存文件后浏览器访问 `http://localhost:8080/` 通常会借助热重载自动刷新。本站离线 Chromium 实测模拟该更新链路:将 `helloState.msg` 由初始 `Welcome to Your Vue.js App` 改为 `欢迎来到蓝色天空 Vue 2 教程!` 后,`<h1>{{ msg }}</h1>` 文本节点即刻同步为新标题。
Vue 2 Webpack 模板项目目录与文件职责
| 目录/文件 | 职责说明 |
| build | 存放 Webpack 构建脚本与开发/生产打包配置代码 |
| config | 存放环境参数、开发服务器端口号与静态资源路径配置,入门可保留默认值 |
| node_modules | 存放 npm/cnpm 安装的全部项目依赖模块 |
| src | 核心开发源码目录,内含 assets(图片等资源)、components(子组件)、App.vue(根组件)与 main.js(入口脚本) |
| static | 存放无需 Webpack 编译转译的纯静态资源(如图片、字体文件) |
| test | 初始单元测试与端到端测试目录,若项目暂不编写测试可按需移除 |
| .xxxx 文件 | 以点号开头的工程配置文件,如 .babelrc、.editorconfig、.eslintrc.js 与 .gitignore |
| index.html | 单页应用首页 HTML 模板入口,可在此添加 meta 信息或外部统计脚本 |
| package.json | 项目清单与脚本配置文件,记录名称、依赖版本及 dev/build 命令 |
| README.md | Markdown 格式的项目说明与启动文档 |
离线核验 Vue 2 项目目录骨架、App.vue 样式与 Hello.vue 数据更新
展开查看收起
"""Offline Playwright Chromium lab for Vue 2 Chapter 03 (vue-directory-structure)."""
import json
import tempfile
from pathlib import Path
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue 2 目录结构与单文件组件实测</title>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
</head>
<body>
<div id="app">
<img id="app-logo" alt="Vue logo" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40'%3E%3Cpolygon points='20,38 2,4 38,4' fill='%2341b883'/%3E%3C/svg%3E">
<div class="hello"><h1 id="hello-msg"></h1></div>
</div>
<script>
(function () {
const HelloComponent = {
name: 'hello',
data() {
return { msg: 'Welcome to Your Vue.js App' };
}
};
const state = HelloComponent.data();
let msgVal = state.msg;
const h1 = document.getElementById('hello-msg');
function render() { h1.textContent = msgVal; }
Object.defineProperty(state, 'msg', {
enumerable: true,
get() { return msgVal; },
set(v) { msgVal = v; render(); }
});
render();
window.helloState = state;
window.appComponent = { name: 'app', components: { Hello: HelloComponent } };
})();
</script>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
# Case 1: Temporary webpack-template project directory layout verification
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "my-project"
for rel in [
"build/webpack.base.conf.js",
"config/index.js",
"node_modules/.placeholder",
"src/assets/logo.png",
"src/components/Hello.vue",
"src/App.vue",
"src/main.js",
"static/.gitkeep",
"test/unit/index.js",
".babelrc",
".editorconfig",
".eslintrc.js",
".gitignore",
"index.html",
"package.json",
"README.md",
]:
fp = root / rel
fp.parent.mkdir(parents=True, exist_ok=True)
fp.write_text("", encoding="utf-8")
top_dirs = sorted(p.name for p in root.iterdir() if p.is_dir())
src_entries = sorted(p.name for p in (root / "src").iterdir())
dot_files = sorted(p.name for p in root.iterdir() if p.is_file() and p.name.startswith("."))
root_files = sorted(p.name for p in root.iterdir() if p.is_file() and not p.name.startswith("."))
res1 = {
"top_dirs": top_dirs,
"src_entries": src_entries,
"dot_files": dot_files,
"root_files": root_files,
}
exp1 = {
"top_dirs": ["build", "config", "node_modules", "src", "static", "test"],
"src_entries": ["App.vue", "assets", "components", "main.js"],
"dot_files": [".babelrc", ".editorconfig", ".eslintrc.js", ".gitignore"],
"root_files": ["README.md", "index.html", "package.json"],
}
cases.append({
"name": "project_root_and_src_layout",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML_DOC)
# Case 2: App.vue SFC structure, component registration & computed styles
res2 = page.evaluate("""() => {
const app = document.getElementById('app');
const cs = getComputedStyle(app);
return {
app_name: window.appComponent.name,
child_registered: 'Hello' in window.appComponent.components,
has_logo: document.getElementById('app-logo') !== null,
text_align: cs.textAlign,
color: cs.color,
margin_top: cs.marginTop
};
}""")
exp2 = {
"app_name": "app",
"child_registered": True,
"has_logo": True,
"text_align": "center",
"color": "rgb(44, 62, 80)",
"margin_top": "60px",
}
cases.append({
"name": "app_vue_sfc_composition",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: Hello.vue data() mutation and live DOM update
res3 = page.evaluate("""() => {
const before = document.getElementById('hello-msg').textContent;
window.helloState.msg = '欢迎来到蓝色天空 Vue 2 教程!';
const after = document.getElementById('hello-msg').textContent;
return { before, after };
}""")
exp3 = {
"before": "Welcome to Your Vue.js App",
"after": "欢迎来到蓝色天空 Vue 2 教程!",
}
cases.append({
"name": "hello_vue_data_update_hmr",
"passed": res3 == exp3,
"expected": exp3,
"actual": res3,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`src/assets` 中的资源会经过 Webpack 模块解析与内联/哈希处理,而 `static/` 中的文件会被原样复制到打包产物目录;组件内 `data` 必须写成函数返回新对象,避免多个组件实例共享同一份状态引用造成相互污染。