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

Vue.js 教程

核对 Vue.js 渐进式视图框架定位、Vue 2.x 生命周期与 EOL 说明、前置技能要求,以及离线 Chromium 中首个声明式渲染与 ES5 响应式实测结果。

学完这一章,你能够

  • 核对 Vue.js 渐进式视图框架定位、Vue 2.x 生命周期与 EOL 说明、前置技能要求,以及离线 Chromium 中首个声明式渲染与 ES5 响应式实测结果。

渐进式框架定位、版本背景与学习前提

Vue.js(读音 `/vjuː/`,与英文 view 近似)是一套用于构建用户界面的渐进式 JavaScript 框架。它聚焦于视图层,采用自底向上的增量开发模式,目标是以简洁直观的 API 实现响应式数据绑定与可组合的视图组件,既能嵌入存量静态页面局部接管交互,也能逐步扩展为完整单页应用。

本系列教程面向 Vue 2.x 生态展开(历史示例最初基于 Vue 2.1.8 等 2.x 版本验证)。需要特别说明的是,Vue 2.0 系列已于 2023 年 12 月 31 日正式停止官方维护(EOL),新建生产项目建议优先评估并采用 Vue 3;维护存量 Vue 2 项目或理解早期选项式 API 与 ES5 响应式原理时,仍可参考本教程内容。

开始学习 Vue 2 之前,需先掌握三项前端基础:用于组织页面结构的 HTML、用于控制排版与视觉外观的 CSS,以及用于处理数据与交互逻辑的 JavaScript。

首个声明式实例与离线 Chromium 实测

入门示例通过 `<div id="app"><p>{{ message }}</p></div>` 声明视图模板并挂载 Vue 实例。本站离线 Chromium 实测核验了声明式绑定、渐进式局部组件接入与 ES5 响应式底层机制:挂载后 `#hello-text` 初始渲染为 `Hello Vue.js!`,将 `vmHello.message` 改为 `Hello Vue 2.x!` 后 DOM 即刻同步更新,而挂载容器外的 `#static-banner` 仍保留原字面量 `{{ untouched }}`;独立挂载的局部组件 `<status-badge>` 渲染为 `<span>Vue 2.x 渐进式组件 (#1)</span>` 且不干扰页面既有结构;检测 `vmHello.$data` 的 `message` 属性描述符确认已定义 `get`/`set` 访问器并与实例代理值一致。

延伸查阅 API 细节与版本迁移指南时,可直接参考 Vue 官方入门指南(https://vuejs.org/guide/introduction.html)、Vue 2 英文模板语法文档(https://v2.vuejs.org/v2/guide/syntax.html)及 Vue 2 中文归档指南(https://v2.cn.vuejs.org/v2/guide/)。

离线 Chromium 核验 Vue 2 Hello World 声明式更新、局部组件挂载与 ES5 响应式描述符

含完整源码 · 217 行
展开查看收起
python
"""Offline Playwright Chromium lab for Vue 2 Chapter 01 (vue-tutorial)."""
import json
from playwright.sync_api import sync_playwright

MINI_VUE2_JS = r"""
(function (global) {
  class Dep {
    constructor() { this.subs = new Set(); }
    depend() { if (Dep.target) this.subs.add(Dep.target); }
    notify() { this.subs.forEach(w => w.update()); }
  }
  Dep.target = null;

  class Watcher {
    constructor(vm, getter, cb) {
      this.vm = vm;
      this.getter = getter;
      this.cb = cb;
      this.value = this.get();
    }
    get() {
      Dep.target = this;
      const val = this.getter.call(this.vm, this.vm);
      Dep.target = null;
      return val;
    }
    update() {
      const oldVal = this.value;
      const newVal = this.get();
      this.value = newVal;
      if (this.cb) this.cb.call(this.vm, newVal, oldVal);
    }
  }

  function observe(data) {
    if (!data || typeof data !== 'object') return;
    Object.keys(data).forEach(key => {
      let val = data[key];
      const dep = new Dep();
      Object.defineProperty(data, key, {
        enumerable: true,
        configurable: true,
        get() { dep.depend(); return val; },
        set(newVal) {
          if (newVal === val) return;
          val = newVal;
          dep.notify();
        }
      });
    });
  }

  function evalExpr(vm, expr) {
    return new Function('with(this){ return (' + expr + '); }').call(vm);
  }

  class Vue {
    constructor(options) {
      this.$options = options || {};
      const rawData = typeof options.data === 'function' ? options.data() : (options.data || {});
      this.$data = rawData;
      observe(rawData);
      Object.keys(rawData).forEach(key => {
        Object.defineProperty(this, key, {
          enumerable: true,
          configurable: true,
          get: () => this.$data[key],
          set: (v) => { this.$data[key] = v; }
        });
      });
      this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el;
      if (this.$el) this._compile(this.$el);
    }
    _compile(node) {
      const components = this.$options.components || {};
      Array.from(node.childNodes).forEach(child => {
        if (child.nodeType === 3 && /\{\{(.+?)\}\}/.test(child.textContent)) {
          const tpl = child.textContent;
          new Watcher(this, () => tpl.replace(/\{\{(.+?)\}\}/g, (_, exp) => evalExpr(this, exp.trim())), val => {
            child.textContent = val;
          });
          child.textContent = tpl.replace(/\{\{(.+?)\}\}/g, (_, exp) => evalExpr(this, exp.trim()));
        } else if (child.nodeType === 1) {
          const tag = child.tagName.toLowerCase();
          if (components[tag]) {
            const compDef = components[tag];
            const wrapper = document.createElement('div');
            wrapper.innerHTML = compDef.template.trim();
            const compEl = wrapper.firstElementChild;
            child.parentNode.replaceChild(compEl, child);
            new Vue({ el: compEl, data: compDef.data });
          } else {
            this._compile(child);
          }
        }
      });
    }
  }
  global.Vue = Vue;
})(window);
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue 2 教程入门实验</title></head>
<body>
  <header id="static-banner">{{{{ untouched }}}}</header>
  <div id="app">
    <p id="hello-text">{{{{ message }}}}</p>
  </div>
  <section id="progressive-widget">
    <status-badge></status-badge>
  </section>
  <script>{MINI_VUE2_JS}</script>
  <script>
    window.vmHello = new Vue({{
      el: '#app',
      data: {{ message: 'Hello Vue.js!' }}
    }});
    window.vmWidget = new Vue({{
      el: '#progressive-widget',
      components: {{
        'status-badge': {{
          data: function () {{ return {{ label: 'Vue 2.x 渐进式组件', count: 1 }}; }},
          template: '<span class="badge">{{{{ label }}}} (#{{{{ count }}}})</span>'
        }}
      }}
    }});
  </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 = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML_DOC)

        # Case 1: Hello World declarative render & reactive update
        res1 = page.evaluate("""() => {
            const initial = document.querySelector('#hello-text').textContent;
            const outside = document.querySelector('#static-banner').textContent;
            window.vmHello.message = 'Hello Vue 2.x!';
            const updated = document.querySelector('#hello-text').textContent;
            return { initial, updated, outside_untouched: outside };
        }""")
        exp1 = {
            "initial": "Hello Vue.js!",
            "updated": "Hello Vue 2.x!",
            "outside_untouched": "{{ untouched }}",
        }
        cases.append({
            "name": "hello_world_declarative_render",
            "passed": res1 == exp1,
            "expected": exp1,
            "actual": res1,
        })

        # Case 2: Progressive bottom-up component adoption inside static page
        res2 = page.evaluate("""() => {
            const badge = document.querySelector('#progressive-widget .badge');
            return {
                tag: badge ? badge.tagName : null,
                text: badge ? badge.textContent : null,
                static_header_preserved: document.querySelector('#static-banner') !== null
            };
        }""")
        exp2 = {
            "tag": "SPAN",
            "text": "Vue 2.x 渐进式组件 (#1)",
            "static_header_preserved": True,
        }
        cases.append({
            "name": "progressive_component_composition",
            "passed": res2 == exp2,
            "expected": exp2,
            "actual": res2,
        })

        # Case 3: ES5 Object.defineProperty reactivity accessor verification
        res3 = page.evaluate("""() => {
            const desc = Object.getOwnPropertyDescriptor(window.vmHello.$data, 'message');
            return {
                has_getter: typeof desc.get === 'function',
                has_setter: typeof desc.set === 'function',
                proxy_matches_data: window.vmHello.message === window.vmHello.$data.message
            };
        }""")
        exp3 = {
            "has_getter": True,
            "has_setter": True,
            "proxy_matches_data": True,
        }
        cases.append({
            "name": "object_defineproperty_reactivity_core",
            "passed": res3 == exp3,
            "expected": exp3,
            "actual": res3,
        })

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 #app 内文本由 Hello Vue.js! 响应式更新为 Hello Vue 2.x!、容器外保留 {{ untouched }}、局部组件输出 span 徽章且 $data 属性具备 getter/setter。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Vue.js

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

下载课程关联工程包:Vue.js

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

开发者可以先在现有静态页面中仅对某个容器(如 #app)引入 Vue 完成数据绑定或局部组件替换,再按需逐步叠加路由、状态管理与构建工具;由于 Vue 2 已于 2023 年 12 月 31 日停止更新,新项目应直接选用 Vue 3,仅在维护存量 Vue 2 代码时沿用 2.x 体系。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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