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

Vue.js 模板语法

核对 Vue 2 文本插值、v-html、属性绑定与 JS 表达式、指令参数与修饰符、v-model 双向绑定、过滤器管道及 v-bind/v-on 缩写实测行为。

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

学完这一章,你能够

模板声明式渲染与四类基础插值

Vue.js 采用基于合法 HTML 的声明式模板语法,将 DOM 结构直接绑定至底层实例数据。结合响应式依赖追踪机制,状态变化时框架能够定位受影响节点并以最小代价完成 DOM 更新。

最常见的数据绑定形式是双大括号文本插值 `{{ message }}`,它会将表达式结果按纯文本转义输出,避免意外注入 HTML 标签;若确实需要把字符串按 HTML 结构插入节点,则使用 `v-html` 指令(仅应用于可信内容以防范 XSS)。本站离线 Chromium 实测同一字段 `<h1>蓝色天空</h1>`:双大括号原样输出字面文本 `<h1>蓝色天空</h1>`,而 `v-html` 在 `#html-box` 内渲染出真实的 `H1` 元素节点且文本为 `蓝色天空`。

双大括号不能直接写在 HTML 标签属性内部,动态属性须借助 `v-bind` 指令(例如根据布尔值 `use` 动态切换 `v-bind:class="{'class1': use}"` 样式类)。此外,Vue 在所有数据绑定位置均支持单个 JavaScript 表达式求值。本站离线实测核验 `{{ 5 + 5 }}` 输出 `10`、三元运算 `ok ? 'YES' : 'NO'` 输出 `YES`、`code.split('').reverse().join('')` 将 `MBSKY` 反转为 `YKSBM`、动态属性 `v-bind:id="'list-' + id"` 成功生成 `#list-1` 节点。

指令、冒号参数与修饰符

指令(Directives)是带有 `v-` 前缀的特殊属性,职责是在绑定表达式的值变化时,将对应的副作用响应式地应用到 DOM 上。例如 `v-if="seen"` 根据 `seen` 的真假决定是否在 DOM 中保留 `<p>` 元素。本站实测初始 `seen=true` 时 `#seen-p` 存在,将 `vm.seen` 置为 `false` 后该节点被移出 DOM。

部分指令支持在名称后用冒号 `:` 指定参数:例如 `v-bind:href="url"` 以 `href` 为参数,告知框架将 `<a>` 的 `href` 属性与 `url` 绑定;`v-on:click="doSomething"` 则以事件名 `click` 为参数,用于监听 DOM 事件。点击勾选复选框实测 `v-bind:class` 使 `#class-box` 挂载 `class1` 且计算背景色变为 `rgb(68, 68, 68)`。

修饰符(Modifiers)是以半角句号 `.` 连接的特殊后缀,用来指明指令的特定绑定行为。例如 `<form v-on:submit.prevent="onSubmit">` 中的 `.prevent` 会在事件触发时自动调用 `event.preventDefault()` 阻止表单默认提交跳转。本站离线 Chromium 真实点击提交按钮测得 `defaultPrevented` 为 `true` 且 `submitCount` 递增至 `1`。

表单双向绑定 v-model 与事件响应 v-on

在 `input`、`select`、`textarea`、`checkbox`、`radio` 等表单控件上,可使用 `v-model` 建立视图与数据的双向绑定:用户编辑表单控件会自动回写实例数据,修改数据也会同步刷新控件值。配合 `v-on` 监听按钮点击即可即时响应交互。本站离线 Chromium 真实输入实测:向 `#model-in` 填入 `Vue2!` 后 `<p>{{ message }}</p>` 立即同步为 `Vue2!`;接着点击绑定了 `reverseMessage` 的按钮,段落文本反转为 `!2euV`,且输入框值同步回显为 `!2euV`。

Vue 2 过滤器与常用指令缩写

Vue 2 允许在 `filters` 选项中自定义文本格式化过滤器,通过管道符 `|` 用于双大括号插值或 `v-bind` 表达式尾部。过滤器函数默认接收上游表达式的值作为第一个参数,并支持多级串联(`message | filterA | filterB`)及传入额外参数(`message | filterA('arg1', arg2)` 中 `'arg1'` 为第二参数、`arg2` 求值结果为第三参数;需注意 Vue 3 已移除过滤器语法,推荐改用计算属性或方法)。本站实测 `capitalize` 将 `'mbsky'` 格式化为 `Mbsky`、`v-bind:data-code="rawId | formatId"` 生成 `item-42`、串联过滤器输出 `Mbsky!`、带参过滤器 `wrap('arg1', arg2)` 输出 `[arg1:mbsky:v2]`。

针对最高频使用的两个指令,Vue 提供了简洁缩写:`v-bind:href="url"` 可简写为 `:href="url"`,`v-on:click="doSomething"` 可简写为 `@click="doSomething"`。本站离线实测核验两种写法的链接 `href` 均为 `https://www.mbsky.com`,点击完整与缩写按钮各一次合计触发 `clickCount = 2`。

离线 Chromium 核验插值、v-html、表达式、指令参数与 .prevent、v-model、过滤器及缩写

python · 阅读源码
"""Offline Playwright Chromium lab for Vue 2 Chapter 05 (vue-template-syntax)."""
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 evalRaw(vm, expr) {
    return new Function('with(this){ return (' + expr + '); }').call(vm);
  }

  function splitFilters(raw) {
    const parts = [];
    let cur = '';
    let inQuote = null;
    for (let i = 0; i < raw.length; i++) {
      const ch = raw[i];
      if (inQuote) {
        cur += ch;
        if (ch === inQuote) inQuote = null;
      } else if (ch === "'" || ch === '"') {
        inQuote = ch;
        cur += ch;
      } else if (ch === '|' && raw[i - 1] !== '|' && raw[i + 1] !== '|') {
        parts.push(cur.trim());
        cur = '';
      } else {
        cur += ch;
      }
    }
    if (cur.trim()) parts.push(cur.trim());
    return parts;
  }

  function evalWithFilters(vm, raw) {
    const parts = splitFilters(raw);
    let val = evalRaw(vm, parts[0]);
    const filters = vm.$options.filters || {};
    for (let i = 1; i < parts.length; i++) {
      const seg = parts[i];
      const m = seg.match(/^([a-zA-Z_$][\w$]*)(?:\((.*)\))?$/);
      if (!m) continue;
      const fn = filters[m[1]];
      if (!fn) continue;
      const args = m[2] ? evalRaw(vm, '[' + m[2] + ']') : [];
      val = fn.apply(null, [val].concat(args));
    }
    return val;
  }

  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 = document.querySelector(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) => evalWithFilters(this, exp.trim()));
          const w = new Watcher(this, render, v => { child.textContent = v; });
          child.textContent = w.value;
        } else if (child.nodeType === 1) {
          this._compileElement(child);
        }
      });
    }
    _compileElement(el) {
      const attrs = Array.from(el.attributes);
      for (const attr of attrs) {
        const name = attr.name;
        const exp = attr.value.trim();
        if (name === 'v-html') {
          el.removeAttribute(name);
          const w = new Watcher(this, () => evalRaw(this, exp), v => { el.innerHTML = v; });
          el.innerHTML = w.value;
        } else if (name === 'v-if') {
          el.removeAttribute(name);
          const anchor = document.createComment('v-if');
          const parent = el.parentNode;
          parent.insertBefore(anchor, el);
          const apply = (cond) => {
            if (cond) {
              if (!el.parentNode) parent.insertBefore(el, anchor.nextSibling);
            } else {
              if (el.parentNode) parent.removeChild(el);
            }
          };
          const w = new Watcher(this, () => Boolean(evalRaw(this, exp)), apply);
          apply(w.value);
        } else if (name === 'v-model') {
          el.removeAttribute(name);
          if (el.type === 'checkbox') {
            const w = new Watcher(this, () => Boolean(evalRaw(this, exp)), v => { el.checked = v; });
            el.checked = w.value;
            el.addEventListener('change', () => { this[exp] = el.checked; });
          } else {
            const w = new Watcher(this, () => evalRaw(this, exp), v => { el.value = v; });
            el.value = w.value;
            el.addEventListener('input', () => { this[exp] = el.value; });
          }
        } else if (name.startsWith('v-bind:') || name.startsWith(':')) {
          el.removeAttribute(name);
          const arg = name.startsWith(':') ? name.slice(1) : name.slice(7);
          const applyAttr = (v) => {
            if (arg === 'class' && typeof v === 'object' && v !== null) {
              Object.keys(v).forEach(cls => { el.classList.toggle(cls, Boolean(v[cls])); });
            } else {
              el.setAttribute(arg, v);
            }
          };
          const w = new Watcher(this, () => evalWithFilters(this, exp), applyAttr);
          applyAttr(w.value);
        } else if (name.startsWith('v-on:') || name.startsWith('@')) {
          el.removeAttribute(name);
          const rawEvent = name.startsWith('@') ? name.slice(1) : name.slice(5);
          const segs = rawEvent.split('.');
          const evtName = segs[0];
          const mods = new Set(segs.slice(1));
          el.addEventListener(evtName, (e) => {
            if (mods.has('prevent')) e.preventDefault();
            if (mods.has('stop')) e.stopPropagation();
            if (typeof this[exp] === 'function') this[exp](e);
            else new Function('$event', 'with(this){ ' + exp + ' }').call(this, e);
          });
        }
      }
      this._compile(el);
    }
  }
  global.Vue = Vue;
})(window);
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>Vue 2 模板语法实验</title>
  <style>
    .class1 {{ background-color: #444444; color: #eeeeee; }}
  </style>
</head>
<body>
  <div id="app">
    <p id="txt-escape">{{{{ rawHtml }}}}</p>
    <div id="html-box" v-html="rawHtml"></div>
    <p id="expr-sum">{{{{ 5 + 5 }}}}</p>
    <p id="expr-tern">{{{{ ok ? 'YES' : 'NO' }}}}</p>
    <p id="expr-rev">{{{{ code.split('').reverse().join('') }}}}</p>
    <div id="expr-id-target" v-bind:id="'list-' + id">动态ID节点</div>

    <input id="chk-use" type="checkbox" v-model="use">
    <div id="class-box" v-bind:class="{{ 'class1': use }}">v-bind:class 指令</div>
    <p id="seen-p" v-if="seen">现在你看到我了</p>
    <a id="link-full" v-bind:href="url">完整绑定</a>
    <a id="link-short" :href="url">缩写绑定</a>
    <button id="btn-full" type="button" v-on:click="bump">完整监听</button>
    <button id="btn-short" type="button" @click="bump">缩写监听</button>

    <form id="demo-form" v-on:submit.prevent="onSubmit">
      <button id="btn-submit" type="submit">提交</button>
    </form>

    <p id="model-out">{{{{ message }}}}</p>
    <input id="model-in" v-model="message">
    <button id="btn-reverse" type="button" v-on:click="reverseMessage">反转字符串</button>

    <p id="flt-cap">{{{{ word | capitalize }}}}</p>
    <div id="flt-bind" v-bind:data-code="rawId | formatId">filter-bind</div>
    <p id="flt-chain">{{{{ word | capitalize | shout }}}}</p>
    <p id="flt-args">{{{{ word | wrap('arg1', arg2) }}}}</p>
  </div>
  <script>{MINI_VUE2_JS}</script>
  <script>
    window.lastSubmitPrevented = false;
    window.submitCount = 0;
    window.clickCount = 0;
    window.vm = new Vue({{
      el: '#app',
      data: {{
        rawHtml: '<h1>蓝色天空</h1>',
        ok: true,
        code: 'MBSKY',
        id: 1,
        use: false,
        seen: true,
        url: 'https://www.mbsky.com',
        message: 'Mbsky!',
        word: 'mbsky',
        rawId: 42,
        arg2: 'v2'
      }},
      methods: {{
        bump: function () {{ window.clickCount += 1; }},
        onSubmit: function (e) {{
          window.lastSubmitPrevented = e.defaultPrevented;
          window.submitCount += 1;
        }},
        reverseMessage: function () {{
          this.message = this.message.split('').reverse().join('');
        }}
      }},
      filters: {{
        capitalize: function (value) {{
          if (!value) return '';
          value = value.toString();
          return value.charAt(0).toUpperCase() + value.slice(1);
        }},
        formatId: function (v) {{ return 'item-' + v; }},
        shout: function (v) {{ return v + '!'; }},
        wrap: function (v, a1, a2) {{ return '[' + a1 + ':' + v + ':' + a2 + ']'; }}
      }}
    }});
  </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: Text interpolation, v-html & JS expressions
        res1 = page.evaluate("""() => ({
            escaped_text: document.getElementById('txt-escape').textContent,
            v_html_tag: document.querySelector('#html-box h1').tagName,
            v_html_text: document.querySelector('#html-box h1').textContent,
            expr_sum: document.getElementById('expr-sum').textContent,
            expr_tern: document.getElementById('expr-tern').textContent,
            expr_rev: document.getElementById('expr-rev').textContent,
            dynamic_id_exists: document.getElementById('list-1') !== null
        })""")
        exp1 = {
            "escaped_text": "<h1>蓝色天空</h1>",
            "v_html_tag": "H1",
            "v_html_text": "蓝色天空",
            "expr_sum": "10",
            "expr_tern": "YES",
            "expr_rev": "YKSBM",
            "dynamic_id_exists": True,
        }
        cases.append({
            "name": "interpolation_text_html_and_expressions",
            "passed": res1 == exp1,
            "expected": exp1,
            "actual": res1,
        })

        # Case 2: Directives (v-bind:class, v-if, v-bind:href/:href, v-on:click/@click)
        before_cls = page.eval_on_selector("#class-box", "el => el.classList.contains('class1')")
        page.click("#chk-use")
        after_cls = page.eval_on_selector("#class-box", "el => ({ has: el.classList.contains('class1'), bg: getComputedStyle(el).backgroundColor })")
        page.click("#btn-full")
        page.click("#btn-short")
        res2 = page.evaluate("""() => {
            const seenBefore = document.getElementById('seen-p') !== null;
            window.vm.seen = false;
            const seenAfter = document.getElementById('seen-p') !== null;
            return {
                seen_before: seenBefore,
                seen_after: seenAfter,
                href_full: document.getElementById('link-full').getAttribute('href'),
                href_short: document.getElementById('link-short').getAttribute('href'),
                click_count: window.clickCount
            };
        }""")
        res2["class1_before"] = before_cls
        res2["class1_after"] = after_cls["has"]
        res2["class1_bg"] = after_cls["bg"]
        exp2 = {
            "seen_before": True,
            "seen_after": False,
            "href_full": "https://www.mbsky.com",
            "href_short": "https://www.mbsky.com",
            "click_count": 2,
            "class1_before": False,
            "class1_after": True,
            "class1_bg": "rgb(68, 68, 68)",
        }
        cases.append({
            "name": "directives_v_bind_v_if_args_and_shorthands",
            "passed": res2 == exp2,
            "expected": exp2,
            "actual": res2,
        })

        # Case 3: .prevent event modifier on form submit
        page.click("#btn-submit")
        res3 = page.evaluate("""() => ({
            default_prevented: window.lastSubmitPrevented,
            submit_count: window.submitCount
        })""")
        exp3 = {"default_prevented": True, "submit_count": 1}
        cases.append({
            "name": "event_modifier_prevent_default",
            "passed": res3 == exp3,
            "expected": exp3,
            "actual": res3,
        })

        # Case 4: v-model two-way binding + v-on string reverse
        page.fill("#model-in", "Vue2!")
        after_input = page.text_content("#model-out")
        page.click("#btn-reverse")
        res4 = {
            "after_input": after_input,
            "after_reverse_text": page.text_content("#model-out"),
            "after_reverse_input_val": page.input_value("#model-in"),
        }
        exp4 = {
            "after_input": "Vue2!",
            "after_reverse_text": "!2euV",
            "after_reverse_input_val": "!2euV",
        }
        cases.append({
            "name": "v_model_and_v_on_reverse_message",
            "passed": res4 == exp4,
            "expected": exp4,
            "actual": res4,
        })

        # Case 5: Filters (single, v-bind, chained, parameterized)
        res5 = page.evaluate("""() => ({
            capitalize: document.getElementById('flt-cap').textContent,
            v_bind_filter: document.getElementById('flt-bind').getAttribute('data-code'),
            chained: document.getElementById('flt-chain').textContent,
            with_args: document.getElementById('flt-args').textContent
        })""")
        exp5 = {
            "capitalize": "Mbsky",
            "v_bind_filter": "item-42",
            "chained": "Mbsky!",
            "with_args": "[arg1:mbsky:v2]",
        }
        cases.append({
            "name": "filters_single_chain_and_args",
            "passed": res5 == exp5,
            "expected": exp5,
            "actual": res5,
        })

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 {{}} 转义与 v-html 渲染 H1、表达式求值、.class1 切换背景 rgb(68,68,68)、submit.prevent 拦截默认提交、v-model 与字符串反转及 4 种过滤器形式。
离线 Chromium 核验插值、v-html、表达式、指令参数与 .prevent、v-model、过滤器及缩写

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

当前源码 SHA256:eb3eb560775208197500842365078d15ba9a5d86beb1cb39ef56fcb4bec30124

下载本站示例源码

本地运行

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

下载Vue.js 模板语法实验

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

ZIP SHA256:c80a3e47ae1a493f7278bfdca7eaddfdd314095d7b053ea5f8f36b7d53dc5df2

常见错误与边界

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

练习与解答

`{{ rawHtml }}` 与 `v-html="rawHtml"` 的渲染行为和安全注意事项有何不同?在 `{{ msg | fn('a', b) }}` 中参数顺序如何对应?

展开参考解答

`{{ rawHtml }}` 会把内容按纯文本转义展示,而 `v-html` 会直接解析并注入真实 HTML 节点,因此切勿对不可信用户输入使用 `v-html` 以防 XSS;过滤器调用中 `msg` 固定作为第一参数,`'a'` 为第二参数,表达式 `b` 的求值结果为第三参数。

规范与官方依据