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

Vue3 教程

核对 Vue 3 渐进式框架定位、前置技术栈、声明式挂载实例及响应式绑定、虚拟 DOM 与工具链核心优势,并以无头 Chromium 离线实测核心机制。

学完这一章,你能够

  • 核对 Vue 3 渐进式框架定位、前置技术栈、声明式挂载实例及响应式绑定、虚拟 DOM 与工具链核心优势,并以无头 Chromium 离线实测核心机制。

Vue 3 定位与渐进式架构

Vue.js(读音类似 /vjuː/,与 view 相近)是一套面向用户界面的渐进式前端框架,聚焦视图层并支持自底向上的增量演进。它通过简洁的 API 组合实现响应式数据绑定与可复用视图组件;本套课程以 Vue 3.x 为主线展开说明。

所谓渐进式框架(与 React、Angular 并列为常见前端技术路线),是指团队无需在项目初期一次性接管整套体系,而是按阶段按需引入路由、状态管理或工程化能力。其工程价值体现在六点:起步门槛低、可与既有页面和第三方库渐进共存、学习曲线平缓、原型搭建迅速、易于与现有技术栈融合,并能避免一开始就陷入高风险的大规模重写。

前置基础与第一个声明式实例

开始 Vue 3.x 实践前,建议具备 HTML 结构标记、CSS 样式布局与 JavaScript 语法及 DOM 事件基础,便于理解模板指令与组件状态流转。

最小声明式挂载示例将模板容器 `<div id="hello-vue" class="demo">{{ message }}</div>` 与响应式状态绑定。本站离线无头 Chromium 实测(`declarative_hello_mount`)确认:挂载后初始文本渲染为 `Hello Vue 3!`,随后仅修改状态属性 `vm.message`,节点文本即自动刷新为 `渐进式视图更新` 且保留原有 `demo` 类名,无需手动调用 DOM 改写接口。

Vue.js 核心特性与参考文档

Vue.js 的核心能力集中在响应式数据绑定、组件化拆分、渐进按需集成(可按需引入 Vue Router 与状态管理方案)以及直观模板语法(如 `v-if`、`v-for`)。本站实测(`template_directives_if_for`)显示:`v-if` 为假时节点不驻留 DOM,切换为真后即时挂载;`v-for` 初始渲染 `HTML`/`CSS`/`JavaScript` 3 项,追加 `Vue 3` 后列表同步增至 4 项。

在渲染效率与交互便利性方面,框架借助虚拟 DOM 差异比对减少真实节点改动,并提供表单双向绑定(`v-model`)、轻量核心运行时与完善工具链(脚手架、Vite、Vue DevTools 及活跃生态)。本站离线实测 `two_way_v_model_binding` 与 `vdom_minimal_patch_and_component` 均通过:表单输入与状态写入实现双向同步;带 key 的虚拟 DOM 仅写入 1 次变动节点并保持未改动 `<li>` 节点引用不变,两个组件计数器实例状态相互独立(`c1:2` 与 `c2:11`)。

延伸查阅可直接参考 Vue 官方中文站点与入门指南(下方官方参考列表已收录),若涉及传统模块打包原理,也可结合现代构建工具与打包器文档对照理解。

在无头 Chromium 中离线验证声明式挂载、指令绑定、双向同步与虚拟 DOM 最小补丁

含完整源码 · 242 行
展开查看收起
python
"""Offline Playwright Chromium verification for Vue 3 Ch01 (tutorial)."""
import json
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_declarative_hello_mount(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"><title>Vue3 Hello</title></head>
<body>
  <div id="hello-vue" class="demo">{{ message }}</div>
  <script>
    function createMiniApp(options) {
      const listeners = new Set();
      const raw = options.data();
      const state = new Proxy(raw, {
        set(target, prop, value) {
          target[prop] = value;
          listeners.forEach((fn) => fn());
          return true;
        }
      });
      return {
        state,
        mount(selector) {
          const el = document.querySelector(selector);
          const tpl = el.textContent;
          const render = () => {
            el.textContent = tpl.replace(/\\{\\{\\s*(\\w+)\\s*\\}\\}/g, (_, k) => String(state[k] ?? ""));
          };
          listeners.add(render);
          render();
          return state;
        }
      };
    }
    const vm = createMiniApp({
      data() { return { message: "Hello Vue 3!" }; }
    }).mount("#hello-vue");
    window.__initial = document.querySelector("#hello-vue").textContent.trim();
    vm.message = "渐进式视图更新";
    window.__updated = document.querySelector("#hello-vue").textContent.trim();
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("({initial: window.__initial, updated: window.__updated, cls: document.querySelector('#hello-vue').className})")
    expected = {"initial": "Hello Vue 3!", "updated": "渐进式视图更新", "cls": "demo"}
    return dict(name="declarative_hello_mount", expected=expected, actual=actual, passed=(actual == expected))


def case_template_directives_if_for(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="app">
    <p id="banner" data-v-if="visible">Vue 3 条件渲染已激活</p>
    <ul id="prereq-list"></ul>
  </div>
  <script>
    const listeners = new Set();
    const state = new Proxy({ visible: false, items: ["HTML", "CSS", "JavaScript"] }, {
      set(t, k, v) { t[k] = v; listeners.forEach((f) => f()); return true; }
    });
    const banner = document.getElementById("banner");
    const placeholder = document.createComment("v-if");
    const parent = banner.parentNode;
    const ul = document.getElementById("prereq-list");
    function render() {
      if (state.visible) {
        if (placeholder.parentNode) parent.replaceChild(banner, placeholder);
      } else {
        if (banner.parentNode) parent.replaceChild(placeholder, banner);
      }
      ul.innerHTML = "";
      for (const item of state.items) {
        const li = document.createElement("li");
        li.textContent = item;
        ul.appendChild(li);
      }
    }
    listeners.add(render);
    render();
    window.__step1 = {
      bannerInDom: !!document.getElementById("banner"),
      items: Array.from(ul.querySelectorAll("li")).map((n) => n.textContent)
    };
    state.visible = true;
    state.items = [...state.items, "Vue 3"];
    window.__step2 = {
      bannerInDom: !!document.getElementById("banner"),
      bannerText: document.getElementById("banner").textContent,
      items: Array.from(ul.querySelectorAll("li")).map((n) => n.textContent)
    };
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("({step1: window.__step1, step2: window.__step2})")
    expected = {
        "step1": {"bannerInDom": False, "items": ["HTML", "CSS", "JavaScript"]},
        "step2": {"bannerInDom": True, "bannerText": "Vue 3 条件渲染已激活", "items": ["HTML", "CSS", "JavaScript", "Vue 3"]},
    }
    return dict(name="template_directives_if_for", expected=expected, actual=actual, passed=(actual == expected))


def case_two_way_v_model_binding(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <input id="course-input" type="text" />
  <span id="course-preview"></span>
  <script>
    const input = document.getElementById("course-input");
    const preview = document.getElementById("course-preview");
    const model = new Proxy({ text: "Vue 3" }, {
      set(t, k, v) {
        t[k] = v;
        if (input.value !== v) input.value = v;
        preview.textContent = v;
        return true;
      }
    });
    input.value = model.text;
    preview.textContent = model.text;
    input.addEventListener("input", (e) => { model.text = e.target.value; });
    window.__model = model;
  </script>
</body></html>"""
    page.set_content(html)
    page.fill("#course-input", "双向数据绑定")
    after_user_input = page.evaluate("({state: window.__model.text, preview: document.getElementById('course-preview').textContent})")
    page.evaluate("window.__model.text = '程序写入同步'")
    after_state_write = page.evaluate("({inputVal: document.getElementById('course-input').value, preview: document.getElementById('course-preview').textContent})")
    actual = {"after_user_input": after_user_input, "after_state_write": after_state_write}
    expected = {
        "after_user_input": {"state": "双向数据绑定", "preview": "双向数据绑定"},
        "after_state_write": {"inputVal": "程序写入同步", "preview": "程序写入同步"},
    }
    return dict(name="two_way_v_model_binding", expected=expected, actual=actual, passed=(actual == expected))


def case_vdom_minimal_patch_and_component(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <ul id="vdom-list"></ul>
  <div id="comp-host"></div>
  <script>
  (() => {
    const ul = document.getElementById("vdom-list");
    let prevVNodes = [];
    function patchList(nextItems) {
      const nextVNodes = nextItems.map((it) => ({ key: it.id, text: it.label, el: null }));
      const prevByKey = new Map(prevVNodes.map((n) => [n.key, n]));
      let domWrites = 0;
      for (const vn of nextVNodes) {
        const old = prevByKey.get(vn.key);
        if (old) {
          vn.el = old.el;
          if (old.text !== vn.text) {
            vn.el.textContent = vn.text;
            domWrites++;
          }
        } else {
          const li = document.createElement("li");
          li.dataset.key = String(vn.key);
          li.textContent = vn.text;
          ul.appendChild(li);
          vn.el = li;
          domWrites++;
        }
      }
      prevVNodes = nextVNodes;
      return domWrites;
    }
    const initWrites = patchList([{ id: 1, label: "响应式" }, { id: 2, label: "组件化" }, { id: 3, label: "虚拟DOM" }]);
    const firstLiBefore = ul.children[0];
    const patchWrites = patchList([{ id: 1, label: "响应式" }, { id: 2, label: "组合式组件" }, { id: 3, label: "虚拟DOM" }]);
    const sameFirstNode = (ul.children[0] === firstLiBefore);

    function mountCounter(host, id, start) {
      let count = start;
      const btn = document.createElement("button");
      btn.id = id;
      const render = () => { btn.textContent = `${id}:${count}`; };
      btn.addEventListener("click", () => { count++; render(); });
      render();
      host.appendChild(btn);
    }
    const host = document.getElementById("comp-host");
    mountCounter(host, "c1", 0);
    mountCounter(host, "c2", 10);
    window.__vdom = { initWrites, patchWrites, sameFirstNode, labels: Array.from(ul.children).map((n) => n.textContent) };
  })();
  </script>
</body></html>"""
    page.set_content(html)
    page.click("#c1")
    page.click("#c1")
    page.click("#c2")
    actual = page.evaluate("({...window.__vdom, c1: document.getElementById('c1').textContent, c2: document.getElementById('c2').textContent})")
    expected = {
        "initWrites": 3,
        "patchWrites": 1,
        "sameFirstNode": True,
        "labels": ["响应式", "组合式组件", "虚拟DOM"],
        "c1": "c1:2",
        "c2": "c2:11",
    }
    return dict(name="vdom_minimal_patch_and_component", 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_declarative_hello_mount(page),
                case_template_directives_if_for(page),
                case_two_way_v_model_binding(page),
                case_vdom_minimal_patch_and_component(page),
            ]
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 #hello-vue 初始与响应式更新文本、v-if/v-for 动态节点增删、v-model 输入与程序双向同步、以及带 key 虚拟 DOM 仅 1 次局部写入与双组件状态隔离。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

渐进式指可从局部视图增强起步,按项目规模逐步引入路由、状态管理与工程构建,而无需一次性重构;修改响应式数据后会触发依赖更新,结合带 key 的虚拟 DOM 差异比对,仅对实际发生变化的 DOM 节点执行最小更新。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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