蓝色天空网mbsky.com · 知识 · 实践 · 创造Vue.js · 本地阅读预览
教程 / 前端开发 / Vue.js

Vue.js 目录结构

核对 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.mdMarkdown 格式的项目说明与启动文档

离线核验 Vue 2 项目目录骨架、App.vue 样式与 Hello.vue 数据更新

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对 6 个顶层目录、src 下 4 项入口、App.vue 计算样式(center / rgb(44,62,80) / 60px)及 Hello.vue msg 响应式切换。
离线核验 Vue 2 项目目录骨架、App.vue 样式与 Hello.vue 数据更新

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:0dd89b7007ab3df7c9fd8dddf093dd5f09fa8318a00a532a61d238eba51cf774

下载本站示例源码

本地运行

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

下载Vue.js 目录结构实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:63318398ef74d48827b8db3e74a0799d6501ddf60906bf2f02be444b50aa104e

常见错误与边界

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

练习与解答

在 Vue 2 Webpack 模板项目中,`src/assets` 与根目录 `static` 存放静态资源有何区别?为什么组件里的 `data` 要写成返回对象的函数?

展开参考解答

`src/assets` 中的资源会经过 Webpack 模块解析与内联/哈希处理,而 `static/` 中的文件会被原样复制到打包产物目录;组件内 `data` 必须写成函数返回新对象,避免多个组件实例共享同一份状态引用造成相互污染。

规范与官方依据