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

Vue.js 起步

核对 Vue 构造函数实例化语法、el 挂载作用域、data 与 methods 定义、共享数据对象响应式代理以及 $data/$el 实例属性实测表现。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Vue 构造器、el 挂载边界与 data / methods 选项

每个 Vue 应用都从通过 `new Vue({ /* 选项 */ })` 创建根实例起步。在选项对象中,最常用的三个基础配置分别是指定挂载目标的 `el`、声明响应式状态属性的 `data`,以及定义实例行为函数的 `methods`。

`el` 参数接收一个 CSS 选择器(如 `'#vue_det'`)或 DOM 元素引用,Vue 的模板编译与后续视图更新严格限定在该容器内部,容器外部的 DOM 节点不受影响。`data` 用于声明参与视图绑定的属性(如 `site`、`url`、`alexa`),`methods` 用于定义可通过 `this` 访问实例属性并返回结果的函数(如 `details()`),模板内则用双大括号 `{{ }}` 输出属性值或函数返回值。本站离线 Chromium 实测验证:`#vue_det` 内准确渲染出 `site : 蓝色天空网`、`url : www.mbsky.com` 与 `蓝色天空网 - 渐进式前端实践`,而位于容器外的 `#outside` 原样保留 `{{ site }}` 未被编译。

响应式数据代理与 $ 前缀实例属性

创建 Vue 实例时,框架会把 `data` 对象中已有属性全部纳入响应式系统并代理到实例 `vm` 上:无论修改 `vm.site` 还是直接修改外部传入的原始 `data` 对象属性,两者指向同一底层数据源,并且视图会自动同步刷新。本站离线 Chromium 实测确认:初始化后 `vm2.site === sharedData.site` 为 `true`;执行 `vm2.site = 'MBSKY'` 后,`sharedData.site` 与页面 DOM 均同步变为 `MBSKY`;反向修改 `sharedData.alexa = 1234` 后,`vm2.alexa` 与页面 DOM 也同步更新为 `1234`。

除用户定义的数据属性外,Vue 实例还暴露了若干内置实例属性与方法,统一使用 `$` 前缀以与用户属性区分。例如 `vm.$data` 指向实例所代理的原始数据对象,`vm.$el` 指向实例挂载的根 DOM 元素。本站离线实测核验 `vm2.$data === sharedData` 为 `true`,`vm2.$el === document.getElementById('vue_shared')` 为 `true` 且元素标签名为 `DIV`。

离线 Chromium 核验 Vue 实例化挂载边界、共享 data 双向代理与 $data/$el 属性

python · 阅读源码
"""Offline Playwright Chromium lab for Vue 2 Chapter 04 (vue-start)."""
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 v = this.getter.call(this.vm);
      Dep.target = null;
      return v;
    }
    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) {
    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 || {};
      this.$data = options.data || {};
      observe(this.$data);
      Object.keys(this.$data).forEach(k => {
        Object.defineProperty(this, k, {
          enumerable: true,
          configurable: true,
          get: () => this.$data[k],
          set: (v) => { this.$data[k] = v; }
        });
      });
      const methods = options.methods || {};
      Object.keys(methods).forEach(m => {
        this[m] = methods[m].bind(this);
      });
      this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el;
      if (this.$el) this._compile(this.$el);
    }
    _compile(node) {
      Array.from(node.childNodes).forEach(child => {
        if (child.nodeType === 3 && /\{\{(.+?)\}\}/.test(child.textContent)) {
          const tpl = child.textContent;
          const render = () => tpl.replace(/\{\{(.+?)\}\}/g, (_, exp) => evalExpr(this, exp.trim()));
          const w = new Watcher(this, render, val => { child.textContent = val; });
          child.textContent = w.value;
        } else if (child.nodeType === 1) {
          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>
  <div id="outside">{{{{ site }}}}</div>
  <div id="vue_det">
    <h1 id="out-site">site : {{{{ site }}}}</h1>
    <h1 id="out-url">url : {{{{ url }}}}</h1>
    <h1 id="out-details">{{{{ details() }}}}</h1>
  </div>
  <div id="vue_shared">
    <p id="s-site">{{{{ site }}}}</p>
    <p id="s-alexa">{{{{ alexa }}}}</p>
  </div>
  <script>{MINI_VUE2_JS}</script>
  <script>
    window.vm1 = new Vue({{
      el: '#vue_det',
      data: {{
        site: '蓝色天空网',
        url: 'www.mbsky.com',
        alexa: '10000'
      }},
      methods: {{
        details: function () {{
          return this.site + ' - 渐进式前端实践';
        }}
      }}
    }});

    window.sharedData = {{
      site: '蓝色天空网',
      url: 'www.mbsky.com',
      alexa: 10000
    }};
    window.vm2 = new Vue({{
      el: '#vue_shared',
      data: window.sharedData
    }});
  </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: el scope, data properties, methods return value, outside isolation
        res1 = page.evaluate("""() => ({
            site_h1: document.getElementById('out-site').textContent,
            url_h1: document.getElementById('out-url').textContent,
            details_h1: document.getElementById('out-details').textContent,
            outside_literal: document.getElementById('outside').textContent
        })""")
        exp1 = {
            "site_h1": "site : 蓝色天空网",
            "url_h1": "url : www.mbsky.com",
            "details_h1": "蓝色天空网 - 渐进式前端实践",
            "outside_literal": "{{ site }}",
        }
        cases.append({
            "name": "vue_instance_el_data_methods",
            "passed": res1 == exp1,
            "expected": exp1,
            "actual": res1,
        })

        # Case 2: Shared data object reference & bidirectional proxy mutation
        res2 = page.evaluate("""() => {
            const sameRefBefore = (window.vm2.site === window.sharedData.site);
            window.vm2.site = 'MBSKY';
            const dataSiteAfterVmWrite = window.sharedData.site;
            const domSiteAfterVmWrite = document.getElementById('s-site').textContent;
            window.sharedData.alexa = 1234;
            const vmAlexaAfterDataWrite = window.vm2.alexa;
            const domAlexaAfterDataWrite = document.getElementById('s-alexa').textContent;
            return {
                same_ref_before: sameRefBefore,
                data_site_after_vm_write: dataSiteAfterVmWrite,
                dom_site_after_vm_write: domSiteAfterVmWrite,
                vm_alexa_after_data_write: vmAlexaAfterDataWrite,
                dom_alexa_after_data_write: domAlexaAfterDataWrite
            };
        }""")
        exp2 = {
            "same_ref_before": True,
            "data_site_after_vm_write": "MBSKY",
            "dom_site_after_vm_write": "MBSKY",
            "vm_alexa_after_data_write": 1234,
            "dom_alexa_after_data_write": "1234",
        }
        cases.append({
            "name": "shared_data_reactivity_proxy",
            "passed": res2 == exp2,
            "expected": exp2,
            "actual": res2,
        })

        # Case 3: $-prefixed built-in instance properties ($data, $el)
        res3 = page.evaluate("""() => ({
            dollar_data_exact: window.vm2.$data === window.sharedData,
            dollar_el_exact: window.vm2.$el === document.getElementById('vue_shared'),
            el_tag: window.vm2.$el.tagName
        })""")
        exp3 = {
            "dollar_data_exact": True,
            "dollar_el_exact": True,
            "el_tag": "DIV",
        }
        cases.append({
            "name": "instance_dollar_properties",
            "passed": res3 == exp3,
            "expected": exp3,
            "actual": res3,
        })

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 #vue_det 内属性与方法插值正常而容器外保留 {{ site }},vm 与 sharedData 互相写入同步刷新 DOM,且 vm.$data 与 vm.$el 严格全等。
离线 Chromium 核验 Vue 实例化挂载边界、共享 data 双向代理与 $data/$el 属性

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

当前源码 SHA256:ab5f4e620b21091e2a7077397f9b3ad809f6339ade640f4e2bbe65981087aa77

下载本站示例源码

本地运行

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

下载Vue.js 起步实验

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

ZIP SHA256:33cdaf7ee0d447b6e06f800f5050961dced075fd4eff93ca0ee80ab0f5b094e1

常见错误与边界

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

练习与解答

为什么 Vue 实例内置属性(如 `$data`、`$el`、`$watch`)都要带 `$` 前缀?把一个外部对象直接传给 `data` 后修改该对象会发生什么?

展开参考解答

因为 Vue 会把 `data` 与 `methods` 中的用户属性直接代理到实例顶层,`$` 前缀用于明确区分框架内置 API,防止命名冲突;由于实例直接观察并代理该外部对象引用,修改原对象属性同样会触发响应式更新并同步刷新视图。

规范与官方依据